| 1 | //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This implements routines for translating from LLVM IR into SelectionDAG IR. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #include "SelectionDAGBuilder.h" |
| 14 | #include "SDNodeDbgValue.h" |
| 15 | #include "llvm/ADT/APFloat.h" |
| 16 | #include "llvm/ADT/APInt.h" |
| 17 | #include "llvm/ADT/ArrayRef.h" |
| 18 | #include "llvm/ADT/BitVector.h" |
| 19 | #include "llvm/ADT/DenseMap.h" |
| 20 | #include "llvm/ADT/None.h" |
| 21 | #include "llvm/ADT/Optional.h" |
| 22 | #include "llvm/ADT/STLExtras.h" |
| 23 | #include "llvm/ADT/SmallPtrSet.h" |
| 24 | #include "llvm/ADT/SmallSet.h" |
| 25 | #include "llvm/ADT/SmallVector.h" |
| 26 | #include "llvm/ADT/StringRef.h" |
| 27 | #include "llvm/ADT/Triple.h" |
| 28 | #include "llvm/ADT/Twine.h" |
| 29 | #include "llvm/Analysis/AliasAnalysis.h" |
| 30 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
| 31 | #include "llvm/Analysis/ConstantFolding.h" |
| 32 | #include "llvm/Analysis/EHPersonalities.h" |
| 33 | #include "llvm/Analysis/Loads.h" |
| 34 | #include "llvm/Analysis/MemoryLocation.h" |
| 35 | #include "llvm/Analysis/TargetLibraryInfo.h" |
| 36 | #include "llvm/Analysis/ValueTracking.h" |
| 37 | #include "llvm/Analysis/VectorUtils.h" |
| 38 | #include "llvm/CodeGen/Analysis.h" |
| 39 | #include "llvm/CodeGen/FunctionLoweringInfo.h" |
| 40 | #include "llvm/CodeGen/GCMetadata.h" |
| 41 | #include "llvm/CodeGen/ISDOpcodes.h" |
| 42 | #include "llvm/CodeGen/MachineBasicBlock.h" |
| 43 | #include "llvm/CodeGen/MachineFrameInfo.h" |
| 44 | #include "llvm/CodeGen/MachineFunction.h" |
| 45 | #include "llvm/CodeGen/MachineInstr.h" |
| 46 | #include "llvm/CodeGen/MachineInstrBuilder.h" |
| 47 | #include "llvm/CodeGen/MachineJumpTableInfo.h" |
| 48 | #include "llvm/CodeGen/MachineMemOperand.h" |
| 49 | #include "llvm/CodeGen/MachineModuleInfo.h" |
| 50 | #include "llvm/CodeGen/MachineOperand.h" |
| 51 | #include "llvm/CodeGen/MachineRegisterInfo.h" |
| 52 | #include "llvm/CodeGen/RuntimeLibcalls.h" |
| 53 | #include "llvm/CodeGen/SelectionDAG.h" |
| 54 | #include "llvm/CodeGen/SelectionDAGNodes.h" |
| 55 | #include "llvm/CodeGen/SelectionDAGTargetInfo.h" |
| 56 | #include "llvm/CodeGen/StackMaps.h" |
| 57 | #include "llvm/CodeGen/SwiftErrorValueTracking.h" |
| 58 | #include "llvm/CodeGen/TargetFrameLowering.h" |
| 59 | #include "llvm/CodeGen/TargetInstrInfo.h" |
| 60 | #include "llvm/CodeGen/TargetLowering.h" |
| 61 | #include "llvm/CodeGen/TargetOpcodes.h" |
| 62 | #include "llvm/CodeGen/TargetRegisterInfo.h" |
| 63 | #include "llvm/CodeGen/TargetSubtargetInfo.h" |
| 64 | #include "llvm/CodeGen/ValueTypes.h" |
| 65 | #include "llvm/CodeGen/WinEHFuncInfo.h" |
| 66 | #include "llvm/IR/Argument.h" |
| 67 | #include "llvm/IR/Attributes.h" |
| 68 | #include "llvm/IR/BasicBlock.h" |
| 69 | #include "llvm/IR/CFG.h" |
| 70 | #include "llvm/IR/CallSite.h" |
| 71 | #include "llvm/IR/CallingConv.h" |
| 72 | #include "llvm/IR/Cheri.h" |
| 73 | #include "llvm/IR/Constant.h" |
| 74 | #include "llvm/IR/ConstantRange.h" |
| 75 | #include "llvm/IR/Constants.h" |
| 76 | #include "llvm/IR/DataLayout.h" |
| 77 | #include "llvm/IR/DebugInfoMetadata.h" |
| 78 | #include "llvm/IR/DebugLoc.h" |
| 79 | #include "llvm/IR/DerivedTypes.h" |
| 80 | #include "llvm/IR/Function.h" |
| 81 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
| 82 | #include "llvm/IR/InlineAsm.h" |
| 83 | #include "llvm/IR/InstrTypes.h" |
| 84 | #include "llvm/IR/Instruction.h" |
| 85 | #include "llvm/IR/Instructions.h" |
| 86 | #include "llvm/IR/IntrinsicInst.h" |
| 87 | #include "llvm/IR/Intrinsics.h" |
| 88 | #include "llvm/IR/LLVMContext.h" |
| 89 | #include "llvm/IR/Metadata.h" |
| 90 | #include "llvm/IR/Module.h" |
| 91 | #include "llvm/IR/Operator.h" |
| 92 | #include "llvm/IR/PatternMatch.h" |
| 93 | #include "llvm/IR/Statepoint.h" |
| 94 | #include "llvm/IR/Type.h" |
| 95 | #include "llvm/IR/User.h" |
| 96 | #include "llvm/IR/Value.h" |
| 97 | #include "llvm/MC/MCContext.h" |
| 98 | #include "llvm/MC/MCSymbol.h" |
| 99 | #include "llvm/Support/AtomicOrdering.h" |
| 100 | #include "llvm/Support/BranchProbability.h" |
| 101 | #include "llvm/Support/Casting.h" |
| 102 | #include "llvm/Support/CodeGen.h" |
| 103 | #include "llvm/Support/CommandLine.h" |
| 104 | #include "llvm/Support/Compiler.h" |
| 105 | #include "llvm/Support/Debug.h" |
| 106 | #include "llvm/Support/ErrorHandling.h" |
| 107 | #include "llvm/Support/MachineValueType.h" |
| 108 | #include "llvm/Support/MathExtras.h" |
| 109 | #include "llvm/Support/raw_ostream.h" |
| 110 | #include "llvm/Target/TargetIntrinsicInfo.h" |
| 111 | #include "llvm/Target/TargetMachine.h" |
| 112 | #include "llvm/Target/TargetOptions.h" |
| 113 | #include "llvm/Transforms/Utils/Local.h" |
| 114 | #include <algorithm> |
| 115 | #include <cassert> |
| 116 | #include <cstddef> |
| 117 | #include <cstdint> |
| 118 | #include <cstring> |
| 119 | #include <iterator> |
| 120 | #include <limits> |
| 121 | #include <numeric> |
| 122 | #include <tuple> |
| 123 | #include <utility> |
| 124 | #include <vector> |
| 125 | |
| 126 | using namespace llvm; |
| 127 | using namespace PatternMatch; |
| 128 | using namespace SwitchCG; |
| 129 | |
| 130 | #define DEBUG_TYPE "isel" |
| 131 | |
| 132 | /// LimitFloatPrecision - Generate low-precision inline sequences for |
| 133 | /// some float libcalls (6, 8 or 12 bits). |
| 134 | static unsigned LimitFloatPrecision; |
| 135 | |
| 136 | static cl::opt<unsigned, true> |
| 137 | LimitFPPrecision("limit-float-precision" , |
| 138 | cl::desc("Generate low-precision inline sequences " |
| 139 | "for some float libcalls" ), |
| 140 | cl::location(LimitFloatPrecision), cl::Hidden, |
| 141 | cl::init(0)); |
| 142 | |
| 143 | static cl::opt<unsigned> SwitchPeelThreshold( |
| 144 | "switch-peel-threshold" , cl::Hidden, cl::init(66), |
| 145 | cl::desc("Set the case probability threshold for peeling the case from a " |
| 146 | "switch statement. A value greater than 100 will void this " |
| 147 | "optimization" )); |
| 148 | |
| 149 | // Limit the width of DAG chains. This is important in general to prevent |
| 150 | // DAG-based analysis from blowing up. For example, alias analysis and |
| 151 | // load clustering may not complete in reasonable time. It is difficult to |
| 152 | // recognize and avoid this situation within each individual analysis, and |
| 153 | // future analyses are likely to have the same behavior. Limiting DAG width is |
| 154 | // the safe approach and will be especially important with global DAGs. |
| 155 | // |
| 156 | // MaxParallelChains default is arbitrarily high to avoid affecting |
| 157 | // optimization, but could be lowered to improve compile time. Any ld-ld-st-st |
| 158 | // sequence over this should have been converted to llvm.memcpy by the |
| 159 | // frontend. It is easy to induce this behavior with .ll code such as: |
| 160 | // %buffer = alloca [4096 x i8] |
| 161 | // %data = load [4096 x i8]* %argPtr |
| 162 | // store [4096 x i8] %data, [4096 x i8]* %buffer |
| 163 | static const unsigned MaxParallelChains = 64; |
| 164 | |
| 165 | // Return the calling convention if the Value passed requires ABI mangling as it |
| 166 | // is a parameter to a function or a return value from a function which is not |
| 167 | // an intrinsic. |
| 168 | static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { |
| 169 | if (auto *R = dyn_cast<ReturnInst>(V)) |
| 170 | return R->getParent()->getParent()->getCallingConv(); |
| 171 | |
| 172 | if (auto *CI = dyn_cast<CallInst>(V)) { |
| 173 | const bool IsInlineAsm = CI->isInlineAsm(); |
| 174 | const bool IsIndirectFunctionCall = |
| 175 | !IsInlineAsm && !CI->getCalledFunction(); |
| 176 | |
| 177 | // It is possible that the call instruction is an inline asm statement or an |
| 178 | // indirect function call in which case the return value of |
| 179 | // getCalledFunction() would be nullptr. |
| 180 | const bool IsInstrinsicCall = |
| 181 | !IsInlineAsm && !IsIndirectFunctionCall && |
| 182 | CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; |
| 183 | |
| 184 | if (!IsInlineAsm && !IsInstrinsicCall) |
| 185 | return CI->getCallingConv(); |
| 186 | } |
| 187 | |
| 188 | return None; |
| 189 | } |
| 190 | |
| 191 | static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, |
| 192 | const SDValue *Parts, unsigned NumParts, |
| 193 | MVT PartVT, EVT ValueVT, const Value *V, |
| 194 | Optional<CallingConv::ID> CC); |
| 195 | |
| 196 | /// getCopyFromParts - Create a value that contains the specified legal parts |
| 197 | /// combined into the value they represent. If the parts combine to a type |
| 198 | /// larger than ValueVT then AssertOp can be used to specify whether the extra |
| 199 | /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT |
| 200 | /// (ISD::AssertSext). |
| 201 | static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, |
| 202 | const SDValue *Parts, unsigned NumParts, |
| 203 | MVT PartVT, EVT ValueVT, const Value *V, |
| 204 | Optional<CallingConv::ID> CC = None, |
| 205 | Optional<ISD::NodeType> AssertOp = None) { |
| 206 | if (ValueVT.isVector()) |
| 207 | return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, |
| 208 | CC); |
| 209 | |
| 210 | assert(NumParts > 0 && "No parts to assemble!" ); |
| 211 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 212 | SDValue Val = Parts[0]; |
| 213 | |
| 214 | if (NumParts > 1) { |
| 215 | // Assemble the value from multiple parts. |
| 216 | if (ValueVT.isInteger()) { |
| 217 | unsigned PartBits = PartVT.getSizeInBits(); |
| 218 | unsigned ValueBits = ValueVT.getSizeInBits(); |
| 219 | |
| 220 | // Assemble the power of 2 part. |
| 221 | unsigned RoundParts = |
| 222 | (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; |
| 223 | unsigned RoundBits = PartBits * RoundParts; |
| 224 | EVT RoundVT = RoundBits == ValueBits ? |
| 225 | ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); |
| 226 | SDValue Lo, Hi; |
| 227 | |
| 228 | EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); |
| 229 | |
| 230 | if (RoundParts > 2) { |
| 231 | Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, |
| 232 | PartVT, HalfVT, V); |
| 233 | Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, |
| 234 | RoundParts / 2, PartVT, HalfVT, V); |
| 235 | } else { |
| 236 | Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); |
| 237 | Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); |
| 238 | } |
| 239 | |
| 240 | if (DAG.getDataLayout().isBigEndian()) |
| 241 | std::swap(Lo, Hi); |
| 242 | |
| 243 | Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); |
| 244 | |
| 245 | if (RoundParts < NumParts) { |
| 246 | // Assemble the trailing non-power-of-2 part. |
| 247 | unsigned OddParts = NumParts - RoundParts; |
| 248 | EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); |
| 249 | Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, |
| 250 | OddVT, V, CC); |
| 251 | |
| 252 | // Combine the round and odd parts. |
| 253 | Lo = Val; |
| 254 | if (DAG.getDataLayout().isBigEndian()) |
| 255 | std::swap(Lo, Hi); |
| 256 | EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); |
| 257 | Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); |
| 258 | Hi = DAG.getNode( |
| 259 | ISD::SHL, DL, TotalVT, Hi, |
| 260 | DAG.getConstant(Lo.getValueSizeInBits(), DL, |
| 261 | TLI.getPointerRangeTy(DAG.getDataLayout()))); |
| 262 | Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); |
| 263 | Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); |
| 264 | } |
| 265 | } else if (PartVT.isFloatingPoint()) { |
| 266 | // FP split into multiple FP parts (for ppcf128) |
| 267 | assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && |
| 268 | "Unexpected split" ); |
| 269 | SDValue Lo, Hi; |
| 270 | Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); |
| 271 | Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); |
| 272 | if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) |
| 273 | std::swap(Lo, Hi); |
| 274 | Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); |
| 275 | } else { |
| 276 | // FP split into integer parts (soft fp) |
| 277 | assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && |
| 278 | !PartVT.isVector() && "Unexpected split" ); |
| 279 | EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); |
| 280 | Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | // There is now one part, held in Val. Correct it to match ValueVT. |
| 285 | // PartEVT is the type of the register class that holds the value. |
| 286 | // ValueVT is the type of the inline asm operation. |
| 287 | EVT PartEVT = Val.getValueType(); |
| 288 | |
| 289 | if (PartEVT == ValueVT) |
| 290 | return Val; |
| 291 | |
| 292 | if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && |
| 293 | ValueVT.bitsLT(PartEVT)) { |
| 294 | // For an FP value in an integer part, we need to truncate to the right |
| 295 | // width first. |
| 296 | PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); |
| 297 | Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); |
| 298 | } |
| 299 | |
| 300 | // Handle types that have the same size. |
| 301 | if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) |
| 302 | return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); |
| 303 | |
| 304 | // Handle types with different sizes. |
| 305 | if (PartEVT.isInteger() && ValueVT.isInteger()) { |
| 306 | if (ValueVT.bitsLT(PartEVT)) { |
| 307 | // For a truncate, see if we have any information to |
| 308 | // indicate whether the truncated bits will always be |
| 309 | // zero or sign-extension. |
| 310 | if (AssertOp.hasValue()) |
| 311 | Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, |
| 312 | DAG.getValueType(ValueVT)); |
| 313 | return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); |
| 314 | } |
| 315 | return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); |
| 316 | } |
| 317 | |
| 318 | if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { |
| 319 | // FP_ROUND's are always exact here. |
| 320 | if (ValueVT.bitsLT(Val.getValueType())) |
| 321 | return DAG.getNode( |
| 322 | ISD::FP_ROUND, DL, ValueVT, Val, |
| 323 | DAG.getTargetConstant(1, DL, |
| 324 | TLI.getPointerRangeTy(DAG.getDataLayout()))); |
| 325 | |
| 326 | return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); |
| 327 | } |
| 328 | |
| 329 | // Handle MMX to a narrower integer type by bitcasting MMX to integer and |
| 330 | // then truncating. |
| 331 | if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && |
| 332 | ValueVT.bitsLT(PartEVT)) { |
| 333 | Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); |
| 334 | return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); |
| 335 | } |
| 336 | |
| 337 | report_fatal_error("Unknown mismatch in getCopyFromParts!" ); |
| 338 | } |
| 339 | |
| 340 | static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, |
| 341 | const Twine &ErrMsg) { |
| 342 | const Instruction *I = dyn_cast_or_null<Instruction>(V); |
| 343 | if (!V) |
| 344 | return Ctx.emitError(ErrMsg); |
| 345 | |
| 346 | const char *AsmError = ", possible invalid constraint for vector type" ; |
| 347 | if (const CallInst *CI = dyn_cast<CallInst>(I)) |
| 348 | if (isa<InlineAsm>(CI->getCalledValue())) |
| 349 | return Ctx.emitError(I, ErrMsg + AsmError); |
| 350 | |
| 351 | return Ctx.emitError(I, ErrMsg); |
| 352 | } |
| 353 | |
| 354 | /// getCopyFromPartsVector - Create a value that contains the specified legal |
| 355 | /// parts combined into the value they represent. If the parts combine to a |
| 356 | /// type larger than ValueVT then AssertOp can be used to specify whether the |
| 357 | /// extra bits are known to be zero (ISD::AssertZext) or sign extended from |
| 358 | /// ValueVT (ISD::AssertSext). |
| 359 | static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, |
| 360 | const SDValue *Parts, unsigned NumParts, |
| 361 | MVT PartVT, EVT ValueVT, const Value *V, |
| 362 | Optional<CallingConv::ID> CallConv) { |
| 363 | assert(ValueVT.isVector() && "Not a vector value" ); |
| 364 | assert(NumParts > 0 && "No parts to assemble!" ); |
| 365 | const bool IsABIRegCopy = CallConv.hasValue(); |
| 366 | |
| 367 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 368 | SDValue Val = Parts[0]; |
| 369 | |
| 370 | // Handle a multi-element vector. |
| 371 | if (NumParts > 1) { |
| 372 | EVT IntermediateVT; |
| 373 | MVT RegisterVT; |
| 374 | unsigned NumIntermediates; |
| 375 | unsigned NumRegs; |
| 376 | |
| 377 | if (IsABIRegCopy) { |
| 378 | NumRegs = TLI.getVectorTypeBreakdownForCallingConv( |
| 379 | *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, |
| 380 | NumIntermediates, RegisterVT); |
| 381 | } else { |
| 382 | NumRegs = |
| 383 | TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, |
| 384 | NumIntermediates, RegisterVT); |
| 385 | } |
| 386 | |
| 387 | assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!" ); |
| 388 | NumParts = NumRegs; // Silence a compiler warning. |
| 389 | assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!" ); |
| 390 | assert(RegisterVT.getSizeInBits() == |
| 391 | Parts[0].getSimpleValueType().getSizeInBits() && |
| 392 | "Part type sizes don't match!" ); |
| 393 | |
| 394 | // Assemble the parts into intermediate operands. |
| 395 | SmallVector<SDValue, 8> Ops(NumIntermediates); |
| 396 | if (NumIntermediates == NumParts) { |
| 397 | // If the register was not expanded, truncate or copy the value, |
| 398 | // as appropriate. |
| 399 | for (unsigned i = 0; i != NumParts; ++i) |
| 400 | Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, |
| 401 | PartVT, IntermediateVT, V); |
| 402 | } else if (NumParts > 0) { |
| 403 | // If the intermediate type was expanded, build the intermediate |
| 404 | // operands from the parts. |
| 405 | assert(NumParts % NumIntermediates == 0 && |
| 406 | "Must expand into a divisible number of parts!" ); |
| 407 | unsigned Factor = NumParts / NumIntermediates; |
| 408 | for (unsigned i = 0; i != NumIntermediates; ++i) |
| 409 | Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, |
| 410 | PartVT, IntermediateVT, V); |
| 411 | } |
| 412 | |
| 413 | // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the |
| 414 | // intermediate operands. |
| 415 | EVT BuiltVectorTy = |
| 416 | EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), |
| 417 | (IntermediateVT.isVector() |
| 418 | ? IntermediateVT.getVectorNumElements() * NumParts |
| 419 | : NumIntermediates)); |
| 420 | Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS |
| 421 | : ISD::BUILD_VECTOR, |
| 422 | DL, BuiltVectorTy, Ops); |
| 423 | } |
| 424 | |
| 425 | // There is now one part, held in Val. Correct it to match ValueVT. |
| 426 | EVT PartEVT = Val.getValueType(); |
| 427 | |
| 428 | if (PartEVT == ValueVT) |
| 429 | return Val; |
| 430 | |
| 431 | if (PartEVT.isVector()) { |
| 432 | // If the element type of the source/dest vectors are the same, but the |
| 433 | // parts vector has more elements than the value vector, then we have a |
| 434 | // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the |
| 435 | // elements we want. |
| 436 | if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { |
| 437 | assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && |
| 438 | "Cannot narrow, it would be a lossy transformation" ); |
| 439 | return DAG.getNode( |
| 440 | ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, |
| 441 | DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); |
| 442 | } |
| 443 | |
| 444 | // Vector/Vector bitcast. |
| 445 | if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) |
| 446 | return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); |
| 447 | |
| 448 | assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && |
| 449 | "Cannot handle this kind of promotion" ); |
| 450 | // Promoted vector extract |
| 451 | return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); |
| 452 | |
| 453 | } |
| 454 | |
| 455 | // Trivial bitcast if the types are the same size and the destination |
| 456 | // vector type is legal. |
| 457 | if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && |
| 458 | TLI.isTypeLegal(ValueVT)) |
| 459 | return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); |
| 460 | |
| 461 | if (ValueVT.getVectorNumElements() != 1) { |
| 462 | // Certain ABIs require that vectors are passed as integers. For vectors |
| 463 | // are the same size, this is an obvious bitcast. |
| 464 | if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { |
| 465 | return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); |
| 466 | } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { |
| 467 | // Bitcast Val back the original type and extract the corresponding |
| 468 | // vector we want. |
| 469 | unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); |
| 470 | EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), |
| 471 | ValueVT.getVectorElementType(), Elts); |
| 472 | Val = DAG.getBitcast(WiderVecType, Val); |
| 473 | return DAG.getNode( |
| 474 | ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, |
| 475 | DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); |
| 476 | } |
| 477 | |
| 478 | diagnosePossiblyInvalidConstraint( |
| 479 | *DAG.getContext(), V, "non-trivial scalar-to-vector conversion" ); |
| 480 | return DAG.getUNDEF(ValueVT); |
| 481 | } |
| 482 | |
| 483 | // Handle cases such as i8 -> <1 x i1> |
| 484 | EVT ValueSVT = ValueVT.getVectorElementType(); |
| 485 | if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) |
| 486 | Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) |
| 487 | : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); |
| 488 | |
| 489 | return DAG.getBuildVector(ValueVT, DL, Val); |
| 490 | } |
| 491 | |
| 492 | static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, |
| 493 | SDValue Val, SDValue *Parts, unsigned NumParts, |
| 494 | MVT PartVT, const Value *V, |
| 495 | Optional<CallingConv::ID> CallConv); |
| 496 | |
| 497 | /// getCopyToParts - Create a series of nodes that contain the specified value |
| 498 | /// split into legal parts. If the parts contain more bits than Val, then, for |
| 499 | /// integers, ExtendKind can be used to specify how to generate the extra bits. |
| 500 | static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, |
| 501 | SDValue *Parts, unsigned NumParts, MVT PartVT, |
| 502 | const Value *V, |
| 503 | Optional<CallingConv::ID> CallConv = None, |
| 504 | ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { |
| 505 | EVT ValueVT = Val.getValueType(); |
| 506 | |
| 507 | // Handle the vector case separately. |
| 508 | if (ValueVT.isVector()) |
| 509 | return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, |
| 510 | CallConv); |
| 511 | |
| 512 | unsigned PartBits = PartVT.getSizeInBits(); |
| 513 | unsigned OrigNumParts = NumParts; |
| 514 | assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && |
| 515 | "Copying to an illegal type!" ); |
| 516 | |
| 517 | if (NumParts == 0) |
| 518 | return; |
| 519 | |
| 520 | assert(!ValueVT.isVector() && "Vector case handled elsewhere" ); |
| 521 | EVT PartEVT = PartVT; |
| 522 | if (PartEVT == ValueVT) { |
| 523 | assert(NumParts == 1 && "No-op copy with multiple parts!" ); |
| 524 | Parts[0] = Val; |
| 525 | return; |
| 526 | } |
| 527 | |
| 528 | if (NumParts * PartBits > ValueVT.getSizeInBits()) { |
| 529 | // If the parts cover more bits than the value has, promote the value. |
| 530 | if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { |
| 531 | assert(NumParts == 1 && "Do not know what to promote to!" ); |
| 532 | Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); |
| 533 | } else if (PartVT.isFatPointer()) { |
| 534 | Val = DAG.getNode(ISD::INTTOPTR, DL, PartVT, Val); |
| 535 | } else { |
| 536 | if (ValueVT.isFloatingPoint()) { |
| 537 | // FP values need to be bitcast, then extended if they are being put |
| 538 | // into a larger container. |
| 539 | ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); |
| 540 | Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); |
| 541 | } |
| 542 | assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && |
| 543 | ValueVT.isInteger() && |
| 544 | "Unknown mismatch!" ); |
| 545 | ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); |
| 546 | Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); |
| 547 | if (PartVT == MVT::x86mmx) |
| 548 | Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); |
| 549 | } |
| 550 | } else if (PartBits == ValueVT.getSizeInBits()) { |
| 551 | // Different types of the same size. |
| 552 | assert(NumParts == 1 && PartEVT != ValueVT); |
| 553 | Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); |
| 554 | } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { |
| 555 | // If the parts cover less bits than value has, truncate the value. |
| 556 | assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && |
| 557 | ValueVT.isInteger() && |
| 558 | "Unknown mismatch!" ); |
| 559 | ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); |
| 560 | Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); |
| 561 | if (PartVT == MVT::x86mmx) |
| 562 | Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); |
| 563 | } |
| 564 | |
| 565 | // The value may have changed - recompute ValueVT. |
| 566 | ValueVT = Val.getValueType(); |
| 567 | assert(NumParts * PartBits == ValueVT.getSizeInBits() && |
| 568 | "Failed to tile the value with PartVT!" ); |
| 569 | |
| 570 | if (NumParts == 1) { |
| 571 | if (PartEVT != ValueVT) { |
| 572 | diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, |
| 573 | "scalar-to-vector conversion failed" ); |
| 574 | Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); |
| 575 | } |
| 576 | |
| 577 | Parts[0] = Val; |
| 578 | return; |
| 579 | } |
| 580 | |
| 581 | // Expand the value into multiple parts. |
| 582 | if (NumParts & (NumParts - 1)) { |
| 583 | // The number of parts is not a power of 2. Split off and copy the tail. |
| 584 | assert(PartVT.isInteger() && ValueVT.isInteger() && |
| 585 | "Do not know what to expand to!" ); |
| 586 | unsigned RoundParts = 1 << Log2_32(NumParts); |
| 587 | unsigned RoundBits = RoundParts * PartBits; |
| 588 | unsigned OddParts = NumParts - RoundParts; |
| 589 | SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, |
| 590 | DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); |
| 591 | |
| 592 | getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, |
| 593 | CallConv); |
| 594 | |
| 595 | if (DAG.getDataLayout().isBigEndian()) |
| 596 | // The odd parts were reversed by getCopyToParts - unreverse them. |
| 597 | std::reverse(Parts + RoundParts, Parts + NumParts); |
| 598 | |
| 599 | NumParts = RoundParts; |
| 600 | ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); |
| 601 | Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); |
| 602 | } |
| 603 | |
| 604 | // The number of parts is a power of 2. Repeatedly bisect the value using |
| 605 | // EXTRACT_ELEMENT. |
| 606 | Parts[0] = DAG.getNode(ISD::BITCAST, DL, |
| 607 | EVT::getIntegerVT(*DAG.getContext(), |
| 608 | ValueVT.getSizeInBits()), |
| 609 | Val); |
| 610 | |
| 611 | for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { |
| 612 | for (unsigned i = 0; i < NumParts; i += StepSize) { |
| 613 | unsigned ThisBits = StepSize * PartBits / 2; |
| 614 | EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); |
| 615 | SDValue &Part0 = Parts[i]; |
| 616 | SDValue &Part1 = Parts[i+StepSize/2]; |
| 617 | |
| 618 | Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, |
| 619 | ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); |
| 620 | Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, |
| 621 | ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); |
| 622 | |
| 623 | if (ThisBits == PartBits && ThisVT != PartVT) { |
| 624 | Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); |
| 625 | Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); |
| 626 | } |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | if (DAG.getDataLayout().isBigEndian()) |
| 631 | std::reverse(Parts, Parts + OrigNumParts); |
| 632 | } |
| 633 | |
| 634 | static SDValue widenVectorToPartType(SelectionDAG &DAG, |
| 635 | SDValue Val, const SDLoc &DL, EVT PartVT) { |
| 636 | if (!PartVT.isVector()) |
| 637 | return SDValue(); |
| 638 | |
| 639 | EVT ValueVT = Val.getValueType(); |
| 640 | unsigned PartNumElts = PartVT.getVectorNumElements(); |
| 641 | unsigned ValueNumElts = ValueVT.getVectorNumElements(); |
| 642 | if (PartNumElts > ValueNumElts && |
| 643 | PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { |
| 644 | EVT ElementVT = PartVT.getVectorElementType(); |
| 645 | // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in |
| 646 | // undef elements. |
| 647 | SmallVector<SDValue, 16> Ops; |
| 648 | DAG.ExtractVectorElements(Val, Ops); |
| 649 | SDValue EltUndef = DAG.getUNDEF(ElementVT); |
| 650 | for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) |
| 651 | Ops.push_back(EltUndef); |
| 652 | |
| 653 | // FIXME: Use CONCAT for 2x -> 4x. |
| 654 | return DAG.getBuildVector(PartVT, DL, Ops); |
| 655 | } |
| 656 | |
| 657 | return SDValue(); |
| 658 | } |
| 659 | |
| 660 | /// getCopyToPartsVector - Create a series of nodes that contain the specified |
| 661 | /// value split into legal parts. |
| 662 | static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, |
| 663 | SDValue Val, SDValue *Parts, unsigned NumParts, |
| 664 | MVT PartVT, const Value *V, |
| 665 | Optional<CallingConv::ID> CallConv) { |
| 666 | EVT ValueVT = Val.getValueType(); |
| 667 | assert(ValueVT.isVector() && "Not a vector" ); |
| 668 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 669 | const bool IsABIRegCopy = CallConv.hasValue(); |
| 670 | |
| 671 | if (NumParts == 1) { |
| 672 | EVT PartEVT = PartVT; |
| 673 | if (PartEVT == ValueVT) { |
| 674 | // Nothing to do. |
| 675 | } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { |
| 676 | // Bitconvert vector->vector case. |
| 677 | Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); |
| 678 | } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { |
| 679 | Val = Widened; |
| 680 | } else if (PartVT.isVector() && |
| 681 | PartEVT.getVectorElementType().bitsGE( |
| 682 | ValueVT.getVectorElementType()) && |
| 683 | PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { |
| 684 | |
| 685 | // Promoted vector extract |
| 686 | Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); |
| 687 | } else { |
| 688 | if (ValueVT.getVectorNumElements() == 1) { |
| 689 | Val = DAG.getNode( |
| 690 | ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, |
| 691 | DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); |
| 692 | } else { |
| 693 | assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && |
| 694 | "lossy conversion of vector to scalar type" ); |
| 695 | EVT IntermediateType = |
| 696 | EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); |
| 697 | Val = DAG.getBitcast(IntermediateType, Val); |
| 698 | Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); |
| 699 | } |
| 700 | } |
| 701 | |
| 702 | assert(Val.getValueType() == PartVT && "Unexpected vector part value type" ); |
| 703 | Parts[0] = Val; |
| 704 | return; |
| 705 | } |
| 706 | |
| 707 | // Handle a multi-element vector. |
| 708 | EVT IntermediateVT; |
| 709 | MVT RegisterVT; |
| 710 | unsigned NumIntermediates; |
| 711 | unsigned NumRegs; |
| 712 | if (IsABIRegCopy) { |
| 713 | NumRegs = TLI.getVectorTypeBreakdownForCallingConv( |
| 714 | *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, |
| 715 | NumIntermediates, RegisterVT); |
| 716 | } else { |
| 717 | NumRegs = |
| 718 | TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, |
| 719 | NumIntermediates, RegisterVT); |
| 720 | } |
| 721 | |
| 722 | assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!" ); |
| 723 | NumParts = NumRegs; // Silence a compiler warning. |
| 724 | assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!" ); |
| 725 | |
| 726 | unsigned IntermediateNumElts = IntermediateVT.isVector() ? |
| 727 | IntermediateVT.getVectorNumElements() : 1; |
| 728 | |
| 729 | // Convert the vector to the appropiate type if necessary. |
| 730 | unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; |
| 731 | |
| 732 | EVT BuiltVectorTy = EVT::getVectorVT( |
| 733 | *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); |
| 734 | MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); |
| 735 | if (ValueVT != BuiltVectorTy) { |
| 736 | if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) |
| 737 | Val = Widened; |
| 738 | |
| 739 | Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); |
| 740 | } |
| 741 | |
| 742 | // Split the vector into intermediate operands. |
| 743 | SmallVector<SDValue, 8> Ops(NumIntermediates); |
| 744 | for (unsigned i = 0; i != NumIntermediates; ++i) { |
| 745 | if (IntermediateVT.isVector()) { |
| 746 | Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, |
| 747 | DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); |
| 748 | } else { |
| 749 | Ops[i] = DAG.getNode( |
| 750 | ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, |
| 751 | DAG.getConstant(i, DL, IdxVT)); |
| 752 | } |
| 753 | } |
| 754 | |
| 755 | // Split the intermediate operands into legal parts. |
| 756 | if (NumParts == NumIntermediates) { |
| 757 | // If the register was not expanded, promote or copy the value, |
| 758 | // as appropriate. |
| 759 | for (unsigned i = 0; i != NumParts; ++i) |
| 760 | getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); |
| 761 | } else if (NumParts > 0) { |
| 762 | // If the intermediate type was expanded, split each the value into |
| 763 | // legal parts. |
| 764 | assert(NumIntermediates != 0 && "division by zero" ); |
| 765 | assert(NumParts % NumIntermediates == 0 && |
| 766 | "Must expand into a divisible number of parts!" ); |
| 767 | unsigned Factor = NumParts / NumIntermediates; |
| 768 | for (unsigned i = 0; i != NumIntermediates; ++i) |
| 769 | getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, |
| 770 | CallConv); |
| 771 | } |
| 772 | } |
| 773 | |
| 774 | RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, |
| 775 | EVT valuevt, Optional<CallingConv::ID> CC) |
| 776 | : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), |
| 777 | RegCount(1, regs.size()), CallConv(CC) {} |
| 778 | |
| 779 | RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, |
| 780 | const DataLayout &DL, unsigned Reg, Type *Ty, |
| 781 | Optional<CallingConv::ID> CC) { |
| 782 | ComputeValueVTs(TLI, DL, Ty, ValueVTs); |
| 783 | |
| 784 | CallConv = CC; |
| 785 | |
| 786 | for (EVT ValueVT : ValueVTs) { |
| 787 | unsigned NumRegs = |
| 788 | isABIMangled() |
| 789 | ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) |
| 790 | : TLI.getNumRegisters(Context, ValueVT); |
| 791 | MVT RegisterVT = |
| 792 | isABIMangled() |
| 793 | ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) |
| 794 | : TLI.getRegisterType(Context, ValueVT); |
| 795 | for (unsigned i = 0; i != NumRegs; ++i) |
| 796 | Regs.push_back(Reg + i); |
| 797 | RegVTs.push_back(RegisterVT); |
| 798 | RegCount.push_back(NumRegs); |
| 799 | Reg += NumRegs; |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, |
| 804 | FunctionLoweringInfo &FuncInfo, |
| 805 | const SDLoc &dl, SDValue &Chain, |
| 806 | SDValue *Flag, const Value *V) const { |
| 807 | // A Value with type {} or [0 x %t] needs no registers. |
| 808 | if (ValueVTs.empty()) |
| 809 | return SDValue(); |
| 810 | |
| 811 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 812 | |
| 813 | // Assemble the legal parts into the final values. |
| 814 | SmallVector<SDValue, 4> Values(ValueVTs.size()); |
| 815 | SmallVector<SDValue, 8> Parts; |
| 816 | for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { |
| 817 | // Copy the legal parts from the registers. |
| 818 | EVT ValueVT = ValueVTs[Value]; |
| 819 | unsigned NumRegs = RegCount[Value]; |
| 820 | MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( |
| 821 | *DAG.getContext(), |
| 822 | CallConv.getValue(), RegVTs[Value]) |
| 823 | : RegVTs[Value]; |
| 824 | |
| 825 | Parts.resize(NumRegs); |
| 826 | for (unsigned i = 0; i != NumRegs; ++i) { |
| 827 | SDValue P; |
| 828 | if (!Flag) { |
| 829 | P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); |
| 830 | } else { |
| 831 | P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); |
| 832 | *Flag = P.getValue(2); |
| 833 | } |
| 834 | |
| 835 | Chain = P.getValue(1); |
| 836 | Parts[i] = P; |
| 837 | |
| 838 | // If the source register was virtual and if we know something about it, |
| 839 | // add an assert node. |
| 840 | if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || |
| 841 | !RegisterVT.isInteger()) |
| 842 | continue; |
| 843 | |
| 844 | const FunctionLoweringInfo::LiveOutInfo *LOI = |
| 845 | FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); |
| 846 | if (!LOI) |
| 847 | continue; |
| 848 | |
| 849 | unsigned RegSize = RegisterVT.getScalarSizeInBits(); |
| 850 | unsigned NumSignBits = LOI->NumSignBits; |
| 851 | unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); |
| 852 | |
| 853 | if (NumZeroBits == RegSize) { |
| 854 | // The current value is a zero. |
| 855 | // Explicitly express that as it would be easier for |
| 856 | // optimizations to kick in. |
| 857 | Parts[i] = DAG.getConstant(0, dl, RegisterVT); |
| 858 | continue; |
| 859 | } |
| 860 | |
| 861 | // FIXME: We capture more information than the dag can represent. For |
| 862 | // now, just use the tightest assertzext/assertsext possible. |
| 863 | bool isSExt; |
| 864 | EVT FromVT(MVT::Other); |
| 865 | if (NumZeroBits) { |
| 866 | FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); |
| 867 | isSExt = false; |
| 868 | } else if (NumSignBits > 1) { |
| 869 | FromVT = |
| 870 | EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); |
| 871 | isSExt = true; |
| 872 | } else { |
| 873 | continue; |
| 874 | } |
| 875 | // Add an assertion node. |
| 876 | assert(FromVT != MVT::Other); |
| 877 | Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, |
| 878 | RegisterVT, P, DAG.getValueType(FromVT)); |
| 879 | } |
| 880 | |
| 881 | Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, |
| 882 | RegisterVT, ValueVT, V, CallConv); |
| 883 | Part += NumRegs; |
| 884 | Parts.clear(); |
| 885 | } |
| 886 | |
| 887 | return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); |
| 888 | } |
| 889 | |
| 890 | void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, |
| 891 | const SDLoc &dl, SDValue &Chain, SDValue *Flag, |
| 892 | const Value *V, |
| 893 | ISD::NodeType PreferredExtendType) const { |
| 894 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 895 | ISD::NodeType ExtendKind = PreferredExtendType; |
| 896 | |
| 897 | // Get the list of the values's legal parts. |
| 898 | unsigned NumRegs = Regs.size(); |
| 899 | SmallVector<SDValue, 8> Parts(NumRegs); |
| 900 | for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { |
| 901 | unsigned NumParts = RegCount[Value]; |
| 902 | |
| 903 | MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( |
| 904 | *DAG.getContext(), |
| 905 | CallConv.getValue(), RegVTs[Value]) |
| 906 | : RegVTs[Value]; |
| 907 | |
| 908 | if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) |
| 909 | ExtendKind = ISD::ZERO_EXTEND; |
| 910 | |
| 911 | getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], |
| 912 | NumParts, RegisterVT, V, CallConv, ExtendKind); |
| 913 | Part += NumParts; |
| 914 | } |
| 915 | |
| 916 | // Copy the parts into the registers. |
| 917 | SmallVector<SDValue, 8> Chains(NumRegs); |
| 918 | for (unsigned i = 0; i != NumRegs; ++i) { |
| 919 | SDValue Part; |
| 920 | if (!Flag) { |
| 921 | Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); |
| 922 | } else { |
| 923 | Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); |
| 924 | *Flag = Part.getValue(1); |
| 925 | } |
| 926 | |
| 927 | Chains[i] = Part.getValue(0); |
| 928 | } |
| 929 | |
| 930 | if (NumRegs == 1 || Flag) |
| 931 | // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is |
| 932 | // flagged to it. That is the CopyToReg nodes and the user are considered |
| 933 | // a single scheduling unit. If we create a TokenFactor and return it as |
| 934 | // chain, then the TokenFactor is both a predecessor (operand) of the |
| 935 | // user as well as a successor (the TF operands are flagged to the user). |
| 936 | // c1, f1 = CopyToReg |
| 937 | // c2, f2 = CopyToReg |
| 938 | // c3 = TokenFactor c1, c2 |
| 939 | // ... |
| 940 | // = op c3, ..., f2 |
| 941 | Chain = Chains[NumRegs-1]; |
| 942 | else |
| 943 | Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); |
| 944 | } |
| 945 | |
| 946 | void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, |
| 947 | unsigned MatchingIdx, const SDLoc &dl, |
| 948 | SelectionDAG &DAG, |
| 949 | std::vector<SDValue> &Ops) const { |
| 950 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 951 | |
| 952 | unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); |
| 953 | if (HasMatching) |
| 954 | Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); |
| 955 | else if (!Regs.empty() && |
| 956 | TargetRegisterInfo::isVirtualRegister(Regs.front())) { |
| 957 | // Put the register class of the virtual registers in the flag word. That |
| 958 | // way, later passes can recompute register class constraints for inline |
| 959 | // assembly as well as normal instructions. |
| 960 | // Don't do this for tied operands that can use the regclass information |
| 961 | // from the def. |
| 962 | const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); |
| 963 | const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); |
| 964 | Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); |
| 965 | } |
| 966 | |
| 967 | SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); |
| 968 | Ops.push_back(Res); |
| 969 | |
| 970 | if (Code == InlineAsm::Kind_Clobber) { |
| 971 | // Clobbers should always have a 1:1 mapping with registers, and may |
| 972 | // reference registers that have illegal (e.g. vector) types. Hence, we |
| 973 | // shouldn't try to apply any sort of splitting logic to them. |
| 974 | assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && |
| 975 | "No 1:1 mapping from clobbers to regs?" ); |
| 976 | unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); |
| 977 | (void)SP; |
| 978 | for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { |
| 979 | Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); |
| 980 | assert( |
| 981 | (Regs[I] != SP || |
| 982 | DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && |
| 983 | "If we clobbered the stack pointer, MFI should know about it." ); |
| 984 | } |
| 985 | return; |
| 986 | } |
| 987 | |
| 988 | for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { |
| 989 | unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); |
| 990 | MVT RegisterVT = RegVTs[Value]; |
| 991 | for (unsigned i = 0; i != NumRegs; ++i) { |
| 992 | assert(Reg < Regs.size() && "Mismatch in # registers expected" ); |
| 993 | unsigned TheReg = Regs[Reg++]; |
| 994 | Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); |
| 995 | } |
| 996 | } |
| 997 | } |
| 998 | |
| 999 | SmallVector<std::pair<unsigned, unsigned>, 4> |
| 1000 | RegsForValue::getRegsAndSizes() const { |
| 1001 | SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; |
| 1002 | unsigned I = 0; |
| 1003 | for (auto CountAndVT : zip_first(RegCount, RegVTs)) { |
| 1004 | unsigned RegCount = std::get<0>(CountAndVT); |
| 1005 | MVT RegisterVT = std::get<1>(CountAndVT); |
| 1006 | unsigned RegisterSize = RegisterVT.getSizeInBits(); |
| 1007 | for (unsigned E = I + RegCount; I != E; ++I) |
| 1008 | OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); |
| 1009 | } |
| 1010 | return OutVec; |
| 1011 | } |
| 1012 | |
| 1013 | void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, |
| 1014 | const TargetLibraryInfo *li) { |
| 1015 | AA = aa; |
| 1016 | GFI = gfi; |
| 1017 | LibInfo = li; |
| 1018 | DL = &DAG.getDataLayout(); |
| 1019 | Context = DAG.getContext(); |
| 1020 | LPadToCallSiteMap.clear(); |
| 1021 | SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); |
| 1022 | } |
| 1023 | |
| 1024 | void SelectionDAGBuilder::clear() { |
| 1025 | NodeMap.clear(); |
| 1026 | UnusedArgNodeMap.clear(); |
| 1027 | PendingLoads.clear(); |
| 1028 | PendingExports.clear(); |
| 1029 | CurInst = nullptr; |
| 1030 | HasTailCall = false; |
| 1031 | SDNodeOrder = LowestSDNodeOrder; |
| 1032 | StatepointLowering.clear(); |
| 1033 | } |
| 1034 | |
| 1035 | void SelectionDAGBuilder::clearDanglingDebugInfo() { |
| 1036 | DanglingDebugInfoMap.clear(); |
| 1037 | } |
| 1038 | |
| 1039 | SDValue SelectionDAGBuilder::getRoot() { |
| 1040 | if (PendingLoads.empty()) |
| 1041 | return DAG.getRoot(); |
| 1042 | |
| 1043 | if (PendingLoads.size() == 1) { |
| 1044 | SDValue Root = PendingLoads[0]; |
| 1045 | DAG.setRoot(Root); |
| 1046 | PendingLoads.clear(); |
| 1047 | return Root; |
| 1048 | } |
| 1049 | |
| 1050 | // Otherwise, we have to make a token factor node. |
| 1051 | SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); |
| 1052 | PendingLoads.clear(); |
| 1053 | DAG.setRoot(Root); |
| 1054 | return Root; |
| 1055 | } |
| 1056 | |
| 1057 | SDValue SelectionDAGBuilder::getControlRoot() { |
| 1058 | SDValue Root = DAG.getRoot(); |
| 1059 | |
| 1060 | if (PendingExports.empty()) |
| 1061 | return Root; |
| 1062 | |
| 1063 | // Turn all of the CopyToReg chains into one factored node. |
| 1064 | if (Root.getOpcode() != ISD::EntryToken) { |
| 1065 | unsigned i = 0, e = PendingExports.size(); |
| 1066 | for (; i != e; ++i) { |
| 1067 | assert(PendingExports[i].getNode()->getNumOperands() > 1); |
| 1068 | if (PendingExports[i].getNode()->getOperand(0) == Root) |
| 1069 | break; // Don't add the root if we already indirectly depend on it. |
| 1070 | } |
| 1071 | |
| 1072 | if (i == e) |
| 1073 | PendingExports.push_back(Root); |
| 1074 | } |
| 1075 | |
| 1076 | Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, |
| 1077 | PendingExports); |
| 1078 | PendingExports.clear(); |
| 1079 | DAG.setRoot(Root); |
| 1080 | return Root; |
| 1081 | } |
| 1082 | |
| 1083 | void SelectionDAGBuilder::visit(const Instruction &I) { |
| 1084 | // Set up outgoing PHI node register values before emitting the terminator. |
| 1085 | if (I.isTerminator()) { |
| 1086 | HandlePHINodesInSuccessorBlocks(I.getParent()); |
| 1087 | } |
| 1088 | |
| 1089 | // Increase the SDNodeOrder if dealing with a non-debug instruction. |
| 1090 | if (!isa<DbgInfoIntrinsic>(I)) |
| 1091 | ++SDNodeOrder; |
| 1092 | |
| 1093 | CurInst = &I; |
| 1094 | |
| 1095 | visit(I.getOpcode(), I); |
| 1096 | |
| 1097 | if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { |
| 1098 | // Propagate the fast-math-flags of this IR instruction to the DAG node that |
| 1099 | // maps to this instruction. |
| 1100 | // TODO: We could handle all flags (nsw, etc) here. |
| 1101 | // TODO: If an IR instruction maps to >1 node, only the final node will have |
| 1102 | // flags set. |
| 1103 | if (SDNode *Node = getNodeForIRValue(&I)) { |
| 1104 | SDNodeFlags IncomingFlags; |
| 1105 | IncomingFlags.copyFMF(*FPMO); |
| 1106 | if (!Node->getFlags().isDefined()) |
| 1107 | Node->setFlags(IncomingFlags); |
| 1108 | else |
| 1109 | Node->intersectFlagsWith(IncomingFlags); |
| 1110 | } |
| 1111 | } |
| 1112 | |
| 1113 | if (!I.isTerminator() && !HasTailCall && |
| 1114 | !isStatepoint(&I)) // statepoints handle their exports internally |
| 1115 | CopyToExportRegsIfNeeded(&I); |
| 1116 | |
| 1117 | CurInst = nullptr; |
| 1118 | } |
| 1119 | |
| 1120 | void SelectionDAGBuilder::visitPHI(const PHINode &) { |
| 1121 | llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!" ); |
| 1122 | } |
| 1123 | |
| 1124 | void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { |
| 1125 | // Note: this doesn't use InstVisitor, because it has to work with |
| 1126 | // ConstantExpr's in addition to instructions. |
| 1127 | switch (Opcode) { |
| 1128 | default: llvm_unreachable("Unknown instruction type encountered!" ); |
| 1129 | // Build the switch statement using the Instruction.def file. |
| 1130 | #define HANDLE_INST(NUM, OPCODE, CLASS) \ |
| 1131 | case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; |
| 1132 | #include "llvm/IR/Instruction.def" |
| 1133 | } |
| 1134 | } |
| 1135 | |
| 1136 | void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, |
| 1137 | const DIExpression *Expr) { |
| 1138 | auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { |
| 1139 | const DbgValueInst *DI = DDI.getDI(); |
| 1140 | DIVariable *DanglingVariable = DI->getVariable(); |
| 1141 | DIExpression *DanglingExpr = DI->getExpression(); |
| 1142 | if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { |
| 1143 | LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n" ); |
| 1144 | return true; |
| 1145 | } |
| 1146 | return false; |
| 1147 | }; |
| 1148 | |
| 1149 | for (auto &DDIMI : DanglingDebugInfoMap) { |
| 1150 | DanglingDebugInfoVector &DDIV = DDIMI.second; |
| 1151 | |
| 1152 | // If debug info is to be dropped, run it through final checks to see |
| 1153 | // whether it can be salvaged. |
| 1154 | for (auto &DDI : DDIV) |
| 1155 | if (isMatchingDbgValue(DDI)) |
| 1156 | salvageUnresolvedDbgValue(DDI); |
| 1157 | |
| 1158 | DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); |
| 1159 | } |
| 1160 | } |
| 1161 | |
| 1162 | // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, |
| 1163 | // generate the debug data structures now that we've seen its definition. |
| 1164 | void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, |
| 1165 | SDValue Val) { |
| 1166 | auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); |
| 1167 | if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) |
| 1168 | return; |
| 1169 | |
| 1170 | DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; |
| 1171 | for (auto &DDI : DDIV) { |
| 1172 | const DbgValueInst *DI = DDI.getDI(); |
| 1173 | assert(DI && "Ill-formed DanglingDebugInfo" ); |
| 1174 | DebugLoc dl = DDI.getdl(); |
| 1175 | unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); |
| 1176 | unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); |
| 1177 | DILocalVariable *Variable = DI->getVariable(); |
| 1178 | DIExpression *Expr = DI->getExpression(); |
| 1179 | assert(Variable->isValidLocationForIntrinsic(dl) && |
| 1180 | "Expected inlined-at fields to agree" ); |
| 1181 | SDDbgValue *SDV; |
| 1182 | if (Val.getNode()) { |
| 1183 | // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a |
| 1184 | // FuncArgumentDbgValue (it would be hoisted to the function entry, and if |
| 1185 | // we couldn't resolve it directly when examining the DbgValue intrinsic |
| 1186 | // in the first place we should not be more successful here). Unless we |
| 1187 | // have some test case that prove this to be correct we should avoid |
| 1188 | // calling EmitFuncArgumentDbgValue here. |
| 1189 | if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { |
| 1190 | LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" |
| 1191 | << DbgSDNodeOrder << "] for:\n " << *DI << "\n" ); |
| 1192 | LLVM_DEBUG(dbgs() << " By mapping to:\n " ; Val.dump()); |
| 1193 | // Increase the SDNodeOrder for the DbgValue here to make sure it is |
| 1194 | // inserted after the definition of Val when emitting the instructions |
| 1195 | // after ISel. An alternative could be to teach |
| 1196 | // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. |
| 1197 | LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() |
| 1198 | << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " |
| 1199 | << ValSDNodeOrder << "\n" ); |
| 1200 | SDV = getDbgValue(Val, Variable, Expr, dl, |
| 1201 | std::max(DbgSDNodeOrder, ValSDNodeOrder)); |
| 1202 | DAG.AddDbgValue(SDV, Val.getNode(), false); |
| 1203 | } else |
| 1204 | LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI |
| 1205 | << "in EmitFuncArgumentDbgValue\n" ); |
| 1206 | } else { |
| 1207 | LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n" ); |
| 1208 | auto Undef = |
| 1209 | UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); |
| 1210 | auto SDV = |
| 1211 | DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); |
| 1212 | DAG.AddDbgValue(SDV, nullptr, false); |
| 1213 | } |
| 1214 | } |
| 1215 | DDIV.clear(); |
| 1216 | } |
| 1217 | |
| 1218 | void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { |
| 1219 | Value *V = DDI.getDI()->getValue(); |
| 1220 | DILocalVariable *Var = DDI.getDI()->getVariable(); |
| 1221 | DIExpression *Expr = DDI.getDI()->getExpression(); |
| 1222 | DebugLoc DL = DDI.getdl(); |
| 1223 | DebugLoc InstDL = DDI.getDI()->getDebugLoc(); |
| 1224 | unsigned SDOrder = DDI.getSDNodeOrder(); |
| 1225 | |
| 1226 | // Currently we consider only dbg.value intrinsics -- we tell the salvager |
| 1227 | // that DW_OP_stack_value is desired. |
| 1228 | assert(isa<DbgValueInst>(DDI.getDI())); |
| 1229 | bool StackValue = true; |
| 1230 | |
| 1231 | // Can this Value can be encoded without any further work? |
| 1232 | if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) |
| 1233 | return; |
| 1234 | |
| 1235 | // Attempt to salvage back through as many instructions as possible. Bail if |
| 1236 | // a non-instruction is seen, such as a constant expression or global |
| 1237 | // variable. FIXME: Further work could recover those too. |
| 1238 | while (isa<Instruction>(V)) { |
| 1239 | Instruction &VAsInst = *cast<Instruction>(V); |
| 1240 | DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); |
| 1241 | |
| 1242 | // If we cannot salvage any further, and haven't yet found a suitable debug |
| 1243 | // expression, bail out. |
| 1244 | if (!NewExpr) |
| 1245 | break; |
| 1246 | |
| 1247 | // New value and expr now represent this debuginfo. |
| 1248 | V = VAsInst.getOperand(0); |
| 1249 | Expr = NewExpr; |
| 1250 | |
| 1251 | // Some kind of simplification occurred: check whether the operand of the |
| 1252 | // salvaged debug expression can be encoded in this DAG. |
| 1253 | if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { |
| 1254 | LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " |
| 1255 | << DDI.getDI() << "\nBy stripping back to:\n " << V); |
| 1256 | return; |
| 1257 | } |
| 1258 | } |
| 1259 | |
| 1260 | // This was the final opportunity to salvage this debug information, and it |
| 1261 | // couldn't be done. Place an undef DBG_VALUE at this location to terminate |
| 1262 | // any earlier variable location. |
| 1263 | auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); |
| 1264 | auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); |
| 1265 | DAG.AddDbgValue(SDV, nullptr, false); |
| 1266 | |
| 1267 | LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() |
| 1268 | << "\n" ); |
| 1269 | LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) |
| 1270 | << "\n" ); |
| 1271 | } |
| 1272 | |
| 1273 | bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, |
| 1274 | DIExpression *Expr, DebugLoc dl, |
| 1275 | DebugLoc InstDL, unsigned Order) { |
| 1276 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 1277 | SDDbgValue *SDV; |
| 1278 | if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || |
| 1279 | isa<ConstantPointerNull>(V)) { |
| 1280 | SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); |
| 1281 | DAG.AddDbgValue(SDV, nullptr, false); |
| 1282 | return true; |
| 1283 | } |
| 1284 | |
| 1285 | // If the Value is a frame index, we can create a FrameIndex debug value |
| 1286 | // without relying on the DAG at all. |
| 1287 | if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { |
| 1288 | auto SI = FuncInfo.StaticAllocaMap.find(AI); |
| 1289 | if (SI != FuncInfo.StaticAllocaMap.end()) { |
| 1290 | auto SDV = |
| 1291 | DAG.getFrameIndexDbgValue(Var, Expr, SI->second, |
| 1292 | /*IsIndirect*/ false, dl, SDNodeOrder); |
| 1293 | // Do not attach the SDNodeDbgValue to an SDNode: this variable location |
| 1294 | // is still available even if the SDNode gets optimized out. |
| 1295 | DAG.AddDbgValue(SDV, nullptr, false); |
| 1296 | return true; |
| 1297 | } |
| 1298 | } |
| 1299 | |
| 1300 | // Do not use getValue() in here; we don't want to generate code at |
| 1301 | // this point if it hasn't been done yet. |
| 1302 | SDValue N = NodeMap[V]; |
| 1303 | if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. |
| 1304 | N = UnusedArgNodeMap[V]; |
| 1305 | if (N.getNode()) { |
| 1306 | if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) |
| 1307 | return true; |
| 1308 | SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); |
| 1309 | DAG.AddDbgValue(SDV, N.getNode(), false); |
| 1310 | return true; |
| 1311 | } |
| 1312 | |
| 1313 | // Special rules apply for the first dbg.values of parameter variables in a |
| 1314 | // function. Identify them by the fact they reference Argument Values, that |
| 1315 | // they're parameters, and they are parameters of the current function. We |
| 1316 | // need to let them dangle until they get an SDNode. |
| 1317 | bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && |
| 1318 | !InstDL.getInlinedAt(); |
| 1319 | if (!IsParamOfFunc) { |
| 1320 | // The value is not used in this block yet (or it would have an SDNode). |
| 1321 | // We still want the value to appear for the user if possible -- if it has |
| 1322 | // an associated VReg, we can refer to that instead. |
| 1323 | auto VMI = FuncInfo.ValueMap.find(V); |
| 1324 | if (VMI != FuncInfo.ValueMap.end()) { |
| 1325 | unsigned Reg = VMI->second; |
| 1326 | // If this is a PHI node, it may be split up into several MI PHI nodes |
| 1327 | // (in FunctionLoweringInfo::set). |
| 1328 | RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, |
| 1329 | V->getType(), None); |
| 1330 | if (RFV.occupiesMultipleRegs()) { |
| 1331 | unsigned Offset = 0; |
| 1332 | unsigned BitsToDescribe = 0; |
| 1333 | if (auto VarSize = Var->getSizeInBits()) |
| 1334 | BitsToDescribe = *VarSize; |
| 1335 | if (auto Fragment = Expr->getFragmentInfo()) |
| 1336 | BitsToDescribe = Fragment->SizeInBits; |
| 1337 | for (auto RegAndSize : RFV.getRegsAndSizes()) { |
| 1338 | unsigned RegisterSize = RegAndSize.second; |
| 1339 | // Bail out if all bits are described already. |
| 1340 | if (Offset >= BitsToDescribe) |
| 1341 | break; |
| 1342 | unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) |
| 1343 | ? BitsToDescribe - Offset |
| 1344 | : RegisterSize; |
| 1345 | auto FragmentExpr = DIExpression::createFragmentExpression( |
| 1346 | Expr, Offset, FragmentSize); |
| 1347 | if (!FragmentExpr) |
| 1348 | continue; |
| 1349 | SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, |
| 1350 | false, dl, SDNodeOrder); |
| 1351 | DAG.AddDbgValue(SDV, nullptr, false); |
| 1352 | Offset += RegisterSize; |
| 1353 | } |
| 1354 | } else { |
| 1355 | SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); |
| 1356 | DAG.AddDbgValue(SDV, nullptr, false); |
| 1357 | } |
| 1358 | return true; |
| 1359 | } |
| 1360 | } |
| 1361 | |
| 1362 | return false; |
| 1363 | } |
| 1364 | |
| 1365 | void SelectionDAGBuilder::resolveOrClearDbgInfo() { |
| 1366 | // Try to fixup any remaining dangling debug info -- and drop it if we can't. |
| 1367 | for (auto &Pair : DanglingDebugInfoMap) |
| 1368 | for (auto &DDI : Pair.second) |
| 1369 | salvageUnresolvedDbgValue(DDI); |
| 1370 | clearDanglingDebugInfo(); |
| 1371 | } |
| 1372 | |
| 1373 | /// getCopyFromRegs - If there was virtual register allocated for the value V |
| 1374 | /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. |
| 1375 | SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { |
| 1376 | DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); |
| 1377 | SDValue Result; |
| 1378 | |
| 1379 | if (It != FuncInfo.ValueMap.end()) { |
| 1380 | unsigned InReg = It->second; |
| 1381 | |
| 1382 | RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), |
| 1383 | DAG.getDataLayout(), InReg, Ty, |
| 1384 | None); // This is not an ABI copy. |
| 1385 | SDValue Chain = DAG.getEntryNode(); |
| 1386 | Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, |
| 1387 | V); |
| 1388 | resolveDanglingDebugInfo(V, Result); |
| 1389 | } |
| 1390 | |
| 1391 | return Result; |
| 1392 | } |
| 1393 | |
| 1394 | /// getValue - Return an SDValue for the given Value. |
| 1395 | SDValue SelectionDAGBuilder::getValue(const Value *V) { |
| 1396 | // If we already have an SDValue for this value, use it. It's important |
| 1397 | // to do this first, so that we don't create a CopyFromReg if we already |
| 1398 | // have a regular SDValue. |
| 1399 | SDValue &N = NodeMap[V]; |
| 1400 | if (N.getNode()) return N; |
| 1401 | |
| 1402 | // If there's a virtual register allocated and initialized for this |
| 1403 | // value, use it. |
| 1404 | if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) |
| 1405 | return copyFromReg; |
| 1406 | |
| 1407 | // Otherwise create a new SDValue and remember it. |
| 1408 | SDValue Val = getValueImpl(V); |
| 1409 | NodeMap[V] = Val; |
| 1410 | resolveDanglingDebugInfo(V, Val); |
| 1411 | return Val; |
| 1412 | } |
| 1413 | |
| 1414 | // Return true if SDValue exists for the given Value |
| 1415 | bool SelectionDAGBuilder::findValue(const Value *V) const { |
| 1416 | return (NodeMap.find(V) != NodeMap.end()) || |
| 1417 | (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); |
| 1418 | } |
| 1419 | |
| 1420 | /// getNonRegisterValue - Return an SDValue for the given Value, but |
| 1421 | /// don't look in FuncInfo.ValueMap for a virtual register. |
| 1422 | SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { |
| 1423 | // If we already have an SDValue for this value, use it. |
| 1424 | SDValue &N = NodeMap[V]; |
| 1425 | if (N.getNode()) { |
| 1426 | if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { |
| 1427 | // Remove the debug location from the node as the node is about to be used |
| 1428 | // in a location which may differ from the original debug location. This |
| 1429 | // is relevant to Constant and ConstantFP nodes because they can appear |
| 1430 | // as constant expressions inside PHI nodes. |
| 1431 | N->setDebugLoc(DebugLoc()); |
| 1432 | } |
| 1433 | return N; |
| 1434 | } |
| 1435 | |
| 1436 | // Otherwise create a new SDValue and remember it. |
| 1437 | SDValue Val = getValueImpl(V); |
| 1438 | NodeMap[V] = Val; |
| 1439 | resolveDanglingDebugInfo(V, Val); |
| 1440 | return Val; |
| 1441 | } |
| 1442 | |
| 1443 | /// getValueImpl - Helper function for getValue and getNonRegisterValue. |
| 1444 | /// Create an SDValue for the given value. |
| 1445 | SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { |
| 1446 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 1447 | |
| 1448 | if (const Constant *C = dyn_cast<Constant>(V)) { |
| 1449 | EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); |
| 1450 | |
| 1451 | if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) |
| 1452 | return DAG.getConstant(*CI, getCurSDLoc(), VT); |
| 1453 | |
| 1454 | if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) |
| 1455 | return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); |
| 1456 | |
| 1457 | if (isa<ConstantPointerNull>(C)) { |
| 1458 | unsigned AS = V->getType()->getPointerAddressSpace(); |
| 1459 | return DAG.getConstant(0, getCurSDLoc(), |
| 1460 | TLI.getPointerTy(DAG.getDataLayout(), AS)); |
| 1461 | } |
| 1462 | |
| 1463 | if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) |
| 1464 | return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); |
| 1465 | |
| 1466 | if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) |
| 1467 | return DAG.getUNDEF(VT); |
| 1468 | |
| 1469 | if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { |
| 1470 | visit(CE->getOpcode(), *CE); |
| 1471 | SDValue N1 = NodeMap[V]; |
| 1472 | assert(N1.getNode() && "visit didn't populate the NodeMap!" ); |
| 1473 | return N1; |
| 1474 | } |
| 1475 | |
| 1476 | if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { |
| 1477 | SmallVector<SDValue, 4> Constants; |
| 1478 | for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); |
| 1479 | OI != OE; ++OI) { |
| 1480 | SDNode *Val = getValue(*OI).getNode(); |
| 1481 | // If the operand is an empty aggregate, there are no values. |
| 1482 | if (!Val) continue; |
| 1483 | // Add each leaf value from the operand to the Constants list |
| 1484 | // to form a flattened list of all the values. |
| 1485 | for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) |
| 1486 | Constants.push_back(SDValue(Val, i)); |
| 1487 | } |
| 1488 | |
| 1489 | return DAG.getMergeValues(Constants, getCurSDLoc()); |
| 1490 | } |
| 1491 | |
| 1492 | if (const ConstantDataSequential *CDS = |
| 1493 | dyn_cast<ConstantDataSequential>(C)) { |
| 1494 | SmallVector<SDValue, 4> Ops; |
| 1495 | for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { |
| 1496 | SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); |
| 1497 | // Add each leaf value from the operand to the Constants list |
| 1498 | // to form a flattened list of all the values. |
| 1499 | for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) |
| 1500 | Ops.push_back(SDValue(Val, i)); |
| 1501 | } |
| 1502 | |
| 1503 | if (isa<ArrayType>(CDS->getType())) |
| 1504 | return DAG.getMergeValues(Ops, getCurSDLoc()); |
| 1505 | return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); |
| 1506 | } |
| 1507 | |
| 1508 | if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { |
| 1509 | assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && |
| 1510 | "Unknown struct or array constant!" ); |
| 1511 | |
| 1512 | SmallVector<EVT, 4> ValueVTs; |
| 1513 | ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); |
| 1514 | unsigned NumElts = ValueVTs.size(); |
| 1515 | if (NumElts == 0) |
| 1516 | return SDValue(); // empty struct |
| 1517 | SmallVector<SDValue, 4> Constants(NumElts); |
| 1518 | for (unsigned i = 0; i != NumElts; ++i) { |
| 1519 | EVT EltVT = ValueVTs[i]; |
| 1520 | if (isa<UndefValue>(C)) |
| 1521 | Constants[i] = DAG.getUNDEF(EltVT); |
| 1522 | else if (EltVT.isFloatingPoint()) |
| 1523 | Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); |
| 1524 | else |
| 1525 | Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); |
| 1526 | } |
| 1527 | |
| 1528 | return DAG.getMergeValues(Constants, getCurSDLoc()); |
| 1529 | } |
| 1530 | |
| 1531 | if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) |
| 1532 | return DAG.getBlockAddress(BA, VT); |
| 1533 | |
| 1534 | VectorType *VecTy = cast<VectorType>(V->getType()); |
| 1535 | unsigned NumElements = VecTy->getNumElements(); |
| 1536 | |
| 1537 | // Now that we know the number and type of the elements, get that number of |
| 1538 | // elements into the Ops array based on what kind of constant it is. |
| 1539 | SmallVector<SDValue, 16> Ops; |
| 1540 | if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { |
| 1541 | for (unsigned i = 0; i != NumElements; ++i) |
| 1542 | Ops.push_back(getValue(CV->getOperand(i))); |
| 1543 | } else { |
| 1544 | assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!" ); |
| 1545 | EVT EltVT = |
| 1546 | TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); |
| 1547 | |
| 1548 | SDValue Op; |
| 1549 | if (EltVT.isFloatingPoint()) |
| 1550 | Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); |
| 1551 | else |
| 1552 | Op = DAG.getConstant(0, getCurSDLoc(), EltVT); |
| 1553 | Ops.assign(NumElements, Op); |
| 1554 | } |
| 1555 | |
| 1556 | // Create a BUILD_VECTOR node. |
| 1557 | return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); |
| 1558 | } |
| 1559 | |
| 1560 | // If this is a static alloca, generate it as the frameindex instead of |
| 1561 | // computation. |
| 1562 | if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { |
| 1563 | DenseMap<const AllocaInst*, int>::iterator SI = |
| 1564 | FuncInfo.StaticAllocaMap.find(AI); |
| 1565 | if (SI != FuncInfo.StaticAllocaMap.end()) |
| 1566 | return DAG.getFrameIndex(SI->second, |
| 1567 | TLI.getFrameIndexTy(DAG.getDataLayout())); |
| 1568 | } |
| 1569 | |
| 1570 | // If this is an instruction which fast-isel has deferred, select it now. |
| 1571 | if (const Instruction *Inst = dyn_cast<Instruction>(V)) { |
| 1572 | unsigned InReg = FuncInfo.InitializeRegForValue(Inst); |
| 1573 | |
| 1574 | RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, |
| 1575 | Inst->getType(), getABIRegCopyCC(V)); |
| 1576 | SDValue Chain = DAG.getEntryNode(); |
| 1577 | return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); |
| 1578 | } |
| 1579 | |
| 1580 | llvm_unreachable("Can't get register for value!" ); |
| 1581 | } |
| 1582 | |
| 1583 | void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { |
| 1584 | auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); |
| 1585 | bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; |
| 1586 | bool IsCoreCLR = Pers == EHPersonality::CoreCLR; |
| 1587 | bool IsSEH = isAsynchronousEHPersonality(Pers); |
| 1588 | bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; |
| 1589 | MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; |
| 1590 | if (!IsSEH) |
| 1591 | CatchPadMBB->setIsEHScopeEntry(); |
| 1592 | // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. |
| 1593 | if (IsMSVCCXX || IsCoreCLR) |
| 1594 | CatchPadMBB->setIsEHFuncletEntry(); |
| 1595 | // Wasm does not need catchpads anymore |
| 1596 | if (!IsWasmCXX) |
| 1597 | DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, |
| 1598 | getControlRoot())); |
| 1599 | } |
| 1600 | |
| 1601 | void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { |
| 1602 | // Update machine-CFG edge. |
| 1603 | MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; |
| 1604 | FuncInfo.MBB->addSuccessor(TargetMBB); |
| 1605 | |
| 1606 | auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); |
| 1607 | bool IsSEH = isAsynchronousEHPersonality(Pers); |
| 1608 | if (IsSEH) { |
| 1609 | // If this is not a fall-through branch or optimizations are switched off, |
| 1610 | // emit the branch. |
| 1611 | if (TargetMBB != NextBlock(FuncInfo.MBB) || |
| 1612 | TM.getOptLevel() == CodeGenOpt::None) |
| 1613 | DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, |
| 1614 | getControlRoot(), DAG.getBasicBlock(TargetMBB))); |
| 1615 | return; |
| 1616 | } |
| 1617 | |
| 1618 | // Figure out the funclet membership for the catchret's successor. |
| 1619 | // This will be used by the FuncletLayout pass to determine how to order the |
| 1620 | // BB's. |
| 1621 | // A 'catchret' returns to the outer scope's color. |
| 1622 | Value *ParentPad = I.getCatchSwitchParentPad(); |
| 1623 | const BasicBlock *SuccessorColor; |
| 1624 | if (isa<ConstantTokenNone>(ParentPad)) |
| 1625 | SuccessorColor = &FuncInfo.Fn->getEntryBlock(); |
| 1626 | else |
| 1627 | SuccessorColor = cast<Instruction>(ParentPad)->getParent(); |
| 1628 | assert(SuccessorColor && "No parent funclet for catchret!" ); |
| 1629 | MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; |
| 1630 | assert(SuccessorColorMBB && "No MBB for SuccessorColor!" ); |
| 1631 | |
| 1632 | // Create the terminator node. |
| 1633 | SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, |
| 1634 | getControlRoot(), DAG.getBasicBlock(TargetMBB), |
| 1635 | DAG.getBasicBlock(SuccessorColorMBB)); |
| 1636 | DAG.setRoot(Ret); |
| 1637 | } |
| 1638 | |
| 1639 | void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { |
| 1640 | // Don't emit any special code for the cleanuppad instruction. It just marks |
| 1641 | // the start of an EH scope/funclet. |
| 1642 | FuncInfo.MBB->setIsEHScopeEntry(); |
| 1643 | auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); |
| 1644 | if (Pers != EHPersonality::Wasm_CXX) { |
| 1645 | FuncInfo.MBB->setIsEHFuncletEntry(); |
| 1646 | FuncInfo.MBB->setIsCleanupFuncletEntry(); |
| 1647 | } |
| 1648 | } |
| 1649 | |
| 1650 | // For wasm, there's alwyas a single catch pad attached to a catchswitch, and |
| 1651 | // the control flow always stops at the single catch pad, as it does for a |
| 1652 | // cleanup pad. In case the exception caught is not of the types the catch pad |
| 1653 | // catches, it will be rethrown by a rethrow. |
| 1654 | static void findWasmUnwindDestinations( |
| 1655 | FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, |
| 1656 | BranchProbability Prob, |
| 1657 | SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> |
| 1658 | &UnwindDests) { |
| 1659 | while (EHPadBB) { |
| 1660 | const Instruction *Pad = EHPadBB->getFirstNonPHI(); |
| 1661 | if (isa<CleanupPadInst>(Pad)) { |
| 1662 | // Stop on cleanup pads. |
| 1663 | UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); |
| 1664 | UnwindDests.back().first->setIsEHScopeEntry(); |
| 1665 | break; |
| 1666 | } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { |
| 1667 | // Add the catchpad handlers to the possible destinations. We don't |
| 1668 | // continue to the unwind destination of the catchswitch for wasm. |
| 1669 | for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { |
| 1670 | UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); |
| 1671 | UnwindDests.back().first->setIsEHScopeEntry(); |
| 1672 | } |
| 1673 | break; |
| 1674 | } else { |
| 1675 | continue; |
| 1676 | } |
| 1677 | } |
| 1678 | } |
| 1679 | |
| 1680 | /// When an invoke or a cleanupret unwinds to the next EH pad, there are |
| 1681 | /// many places it could ultimately go. In the IR, we have a single unwind |
| 1682 | /// destination, but in the machine CFG, we enumerate all the possible blocks. |
| 1683 | /// This function skips over imaginary basic blocks that hold catchswitch |
| 1684 | /// instructions, and finds all the "real" machine |
| 1685 | /// basic block destinations. As those destinations may not be successors of |
| 1686 | /// EHPadBB, here we also calculate the edge probability to those destinations. |
| 1687 | /// The passed-in Prob is the edge probability to EHPadBB. |
| 1688 | static void findUnwindDestinations( |
| 1689 | FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, |
| 1690 | BranchProbability Prob, |
| 1691 | SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> |
| 1692 | &UnwindDests) { |
| 1693 | EHPersonality Personality = |
| 1694 | classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); |
| 1695 | bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; |
| 1696 | bool IsCoreCLR = Personality == EHPersonality::CoreCLR; |
| 1697 | bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; |
| 1698 | bool IsSEH = isAsynchronousEHPersonality(Personality); |
| 1699 | |
| 1700 | if (IsWasmCXX) { |
| 1701 | findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); |
| 1702 | assert(UnwindDests.size() <= 1 && |
| 1703 | "There should be at most one unwind destination for wasm" ); |
| 1704 | return; |
| 1705 | } |
| 1706 | |
| 1707 | while (EHPadBB) { |
| 1708 | const Instruction *Pad = EHPadBB->getFirstNonPHI(); |
| 1709 | BasicBlock *NewEHPadBB = nullptr; |
| 1710 | if (isa<LandingPadInst>(Pad)) { |
| 1711 | // Stop on landingpads. They are not funclets. |
| 1712 | UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); |
| 1713 | break; |
| 1714 | } else if (isa<CleanupPadInst>(Pad)) { |
| 1715 | // Stop on cleanup pads. Cleanups are always funclet entries for all known |
| 1716 | // personalities. |
| 1717 | UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); |
| 1718 | UnwindDests.back().first->setIsEHScopeEntry(); |
| 1719 | UnwindDests.back().first->setIsEHFuncletEntry(); |
| 1720 | break; |
| 1721 | } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { |
| 1722 | // Add the catchpad handlers to the possible destinations. |
| 1723 | for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { |
| 1724 | UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); |
| 1725 | // For MSVC++ and the CLR, catchblocks are funclets and need prologues. |
| 1726 | if (IsMSVCCXX || IsCoreCLR) |
| 1727 | UnwindDests.back().first->setIsEHFuncletEntry(); |
| 1728 | if (!IsSEH) |
| 1729 | UnwindDests.back().first->setIsEHScopeEntry(); |
| 1730 | } |
| 1731 | NewEHPadBB = CatchSwitch->getUnwindDest(); |
| 1732 | } else { |
| 1733 | continue; |
| 1734 | } |
| 1735 | |
| 1736 | BranchProbabilityInfo *BPI = FuncInfo.BPI; |
| 1737 | if (BPI && NewEHPadBB) |
| 1738 | Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); |
| 1739 | EHPadBB = NewEHPadBB; |
| 1740 | } |
| 1741 | } |
| 1742 | |
| 1743 | void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { |
| 1744 | // Update successor info. |
| 1745 | SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; |
| 1746 | auto UnwindDest = I.getUnwindDest(); |
| 1747 | BranchProbabilityInfo *BPI = FuncInfo.BPI; |
| 1748 | BranchProbability UnwindDestProb = |
| 1749 | (BPI && UnwindDest) |
| 1750 | ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) |
| 1751 | : BranchProbability::getZero(); |
| 1752 | findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); |
| 1753 | for (auto &UnwindDest : UnwindDests) { |
| 1754 | UnwindDest.first->setIsEHPad(); |
| 1755 | addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); |
| 1756 | } |
| 1757 | FuncInfo.MBB->normalizeSuccProbs(); |
| 1758 | |
| 1759 | // Create the terminator node. |
| 1760 | SDValue Ret = |
| 1761 | DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); |
| 1762 | DAG.setRoot(Ret); |
| 1763 | } |
| 1764 | |
| 1765 | void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { |
| 1766 | report_fatal_error("visitCatchSwitch not yet implemented!" ); |
| 1767 | } |
| 1768 | |
| 1769 | void SelectionDAGBuilder::visitRet(const ReturnInst &I) { |
| 1770 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 1771 | auto &DL = DAG.getDataLayout(); |
| 1772 | SDValue Chain = getControlRoot(); |
| 1773 | SmallVector<ISD::OutputArg, 8> Outs; |
| 1774 | SmallVector<SDValue, 8> OutVals; |
| 1775 | |
| 1776 | // Calls to @llvm.experimental.deoptimize don't generate a return value, so |
| 1777 | // lower |
| 1778 | // |
| 1779 | // %val = call <ty> @llvm.experimental.deoptimize() |
| 1780 | // ret <ty> %val |
| 1781 | // |
| 1782 | // differently. |
| 1783 | if (I.getParent()->getTerminatingDeoptimizeCall()) { |
| 1784 | LowerDeoptimizingReturn(); |
| 1785 | return; |
| 1786 | } |
| 1787 | |
| 1788 | if (!FuncInfo.CanLowerReturn) { |
| 1789 | unsigned DemoteReg = FuncInfo.DemoteRegister; |
| 1790 | const Function *F = I.getParent()->getParent(); |
| 1791 | |
| 1792 | // Emit a store of the return value through the virtual register. |
| 1793 | // Leave Outs empty so that LowerReturn won't try to load return |
| 1794 | // registers the usual way. |
| 1795 | SmallVector<EVT, 1> PtrValueVTs; |
| 1796 | ComputeValueVTs(TLI, DL, |
| 1797 | F->getReturnType()->getPointerTo( |
| 1798 | DAG.getDataLayout().getAllocaAddrSpace()), |
| 1799 | PtrValueVTs); |
| 1800 | |
| 1801 | SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), |
| 1802 | DemoteReg, PtrValueVTs[0]); |
| 1803 | SDValue RetOp = getValue(I.getOperand(0)); |
| 1804 | |
| 1805 | SmallVector<EVT, 4> ValueVTs, MemVTs; |
| 1806 | SmallVector<uint64_t, 4> Offsets; |
| 1807 | ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, |
| 1808 | &Offsets); |
| 1809 | unsigned NumValues = ValueVTs.size(); |
| 1810 | |
| 1811 | SmallVector<SDValue, 4> Chains(NumValues); |
| 1812 | unsigned BaseAlign = DL.getABITypeAlignment(I.getOperand(0)->getType()); |
| 1813 | for (unsigned i = 0; i != NumValues; ++i) { |
| 1814 | // An aggregate return value cannot wrap around the address space, so |
| 1815 | // offsets to its parts don't wrap either. |
| 1816 | SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); |
| 1817 | |
| 1818 | SDValue Val = RetOp.getValue(i); |
| 1819 | if (MemVTs[i] != ValueVTs[i]) |
| 1820 | Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); |
| 1821 | Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, |
| 1822 | // FIXME: better loc info would be nice. |
| 1823 | Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), |
| 1824 | MinAlign(BaseAlign, Offsets[i])); |
| 1825 | } |
| 1826 | |
| 1827 | Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), |
| 1828 | MVT::Other, Chains); |
| 1829 | } else if (I.getNumOperands() != 0) { |
| 1830 | SmallVector<EVT, 4> ValueVTs; |
| 1831 | ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); |
| 1832 | unsigned NumValues = ValueVTs.size(); |
| 1833 | if (NumValues) { |
| 1834 | SDValue RetOp = getValue(I.getOperand(0)); |
| 1835 | |
| 1836 | const Function *F = I.getParent()->getParent(); |
| 1837 | |
| 1838 | bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( |
| 1839 | I.getOperand(0)->getType(), F->getCallingConv(), |
| 1840 | /*IsVarArg*/ false); |
| 1841 | |
| 1842 | ISD::NodeType ExtendKind = ISD::ANY_EXTEND; |
| 1843 | if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, |
| 1844 | Attribute::SExt)) |
| 1845 | ExtendKind = ISD::SIGN_EXTEND; |
| 1846 | else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, |
| 1847 | Attribute::ZExt)) |
| 1848 | ExtendKind = ISD::ZERO_EXTEND; |
| 1849 | |
| 1850 | LLVMContext &Context = F->getContext(); |
| 1851 | bool RetInReg = F->getAttributes().hasAttribute( |
| 1852 | AttributeList::ReturnIndex, Attribute::InReg); |
| 1853 | |
| 1854 | for (unsigned j = 0; j != NumValues; ++j) { |
| 1855 | EVT VT = ValueVTs[j]; |
| 1856 | |
| 1857 | if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) |
| 1858 | VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); |
| 1859 | |
| 1860 | CallingConv::ID CC = F->getCallingConv(); |
| 1861 | |
| 1862 | unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); |
| 1863 | MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); |
| 1864 | SmallVector<SDValue, 4> Parts(NumParts); |
| 1865 | getCopyToParts(DAG, getCurSDLoc(), |
| 1866 | SDValue(RetOp.getNode(), RetOp.getResNo() + j), |
| 1867 | &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); |
| 1868 | |
| 1869 | // 'inreg' on function refers to return value |
| 1870 | ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); |
| 1871 | if (RetInReg) |
| 1872 | Flags.setInReg(); |
| 1873 | |
| 1874 | if (I.getOperand(0)->getType()->isPointerTy()) { |
| 1875 | Flags.setPointer(); |
| 1876 | Flags.setPointerAddrSpace( |
| 1877 | cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); |
| 1878 | } |
| 1879 | |
| 1880 | if (NeedsRegBlock) { |
| 1881 | Flags.setInConsecutiveRegs(); |
| 1882 | if (j == NumValues - 1) |
| 1883 | Flags.setInConsecutiveRegsLast(); |
| 1884 | } |
| 1885 | |
| 1886 | // Propagate extension type if any |
| 1887 | if (ExtendKind == ISD::SIGN_EXTEND) |
| 1888 | Flags.setSExt(); |
| 1889 | else if (ExtendKind == ISD::ZERO_EXTEND) |
| 1890 | Flags.setZExt(); |
| 1891 | |
| 1892 | for (unsigned i = 0; i < NumParts; ++i) { |
| 1893 | Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), |
| 1894 | VT, /*isfixed=*/true, 0, 0)); |
| 1895 | OutVals.push_back(Parts[i]); |
| 1896 | } |
| 1897 | } |
| 1898 | } |
| 1899 | } |
| 1900 | |
| 1901 | // Push in swifterror virtual register as the last element of Outs. This makes |
| 1902 | // sure swifterror virtual register will be returned in the swifterror |
| 1903 | // physical register. |
| 1904 | const Function *F = I.getParent()->getParent(); |
| 1905 | if (TLI.supportSwiftError() && |
| 1906 | F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { |
| 1907 | assert(SwiftError.getFunctionArg() && "Need a swift error argument" ); |
| 1908 | ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); |
| 1909 | Flags.setSwiftError(); |
| 1910 | Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerRangeTy(DL)) /*vt*/, |
| 1911 | EVT(TLI.getPointerRangeTy(DL)) /*argvt*/, |
| 1912 | true /*isfixed*/, 1 /*origidx*/, |
| 1913 | 0 /*partOffs*/)); |
| 1914 | // Create SDNode for the swifterror virtual register. |
| 1915 | OutVals.push_back( |
| 1916 | DAG.getRegister(SwiftError.getOrCreateVRegUseAt( |
| 1917 | &I, FuncInfo.MBB, SwiftError.getFunctionArg()), |
| 1918 | EVT(TLI.getPointerTy(DL, DL.getAllocaAddrSpace())))); |
| 1919 | } |
| 1920 | |
| 1921 | bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); |
| 1922 | CallingConv::ID CallConv = |
| 1923 | DAG.getMachineFunction().getFunction().getCallingConv(); |
| 1924 | Chain = DAG.getTargetLoweringInfo().LowerReturn( |
| 1925 | Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); |
| 1926 | |
| 1927 | // Verify that the target's LowerReturn behaved as expected. |
| 1928 | assert(Chain.getNode() && Chain.getValueType() == MVT::Other && |
| 1929 | "LowerReturn didn't return a valid chain!" ); |
| 1930 | |
| 1931 | // Update the DAG with the new chain value resulting from return lowering. |
| 1932 | DAG.setRoot(Chain); |
| 1933 | } |
| 1934 | |
| 1935 | /// CopyToExportRegsIfNeeded - If the given value has virtual registers |
| 1936 | /// created for it, emit nodes to copy the value into the virtual |
| 1937 | /// registers. |
| 1938 | void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { |
| 1939 | // Skip empty types |
| 1940 | if (V->getType()->isEmptyTy()) |
| 1941 | return; |
| 1942 | |
| 1943 | DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); |
| 1944 | if (VMI != FuncInfo.ValueMap.end()) { |
| 1945 | assert(!V->use_empty() && "Unused value assigned virtual registers!" ); |
| 1946 | CopyValueToVirtualRegister(V, VMI->second); |
| 1947 | } |
| 1948 | } |
| 1949 | |
| 1950 | /// ExportFromCurrentBlock - If this condition isn't known to be exported from |
| 1951 | /// the current basic block, add it to ValueMap now so that we'll get a |
| 1952 | /// CopyTo/FromReg. |
| 1953 | void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { |
| 1954 | // No need to export constants. |
| 1955 | if (!isa<Instruction>(V) && !isa<Argument>(V)) return; |
| 1956 | |
| 1957 | // Already exported? |
| 1958 | if (FuncInfo.isExportedInst(V)) return; |
| 1959 | |
| 1960 | unsigned Reg = FuncInfo.InitializeRegForValue(V); |
| 1961 | CopyValueToVirtualRegister(V, Reg); |
| 1962 | } |
| 1963 | |
| 1964 | bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, |
| 1965 | const BasicBlock *FromBB) { |
| 1966 | // The operands of the setcc have to be in this block. We don't know |
| 1967 | // how to export them from some other block. |
| 1968 | if (const Instruction *VI = dyn_cast<Instruction>(V)) { |
| 1969 | // Can export from current BB. |
| 1970 | if (VI->getParent() == FromBB) |
| 1971 | return true; |
| 1972 | |
| 1973 | // Is already exported, noop. |
| 1974 | return FuncInfo.isExportedInst(V); |
| 1975 | } |
| 1976 | |
| 1977 | // If this is an argument, we can export it if the BB is the entry block or |
| 1978 | // if it is already exported. |
| 1979 | if (isa<Argument>(V)) { |
| 1980 | if (FromBB == &FromBB->getParent()->getEntryBlock()) |
| 1981 | return true; |
| 1982 | |
| 1983 | // Otherwise, can only export this if it is already exported. |
| 1984 | return FuncInfo.isExportedInst(V); |
| 1985 | } |
| 1986 | |
| 1987 | // Otherwise, constants can always be exported. |
| 1988 | return true; |
| 1989 | } |
| 1990 | |
| 1991 | /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. |
| 1992 | BranchProbability |
| 1993 | SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, |
| 1994 | const MachineBasicBlock *Dst) const { |
| 1995 | BranchProbabilityInfo *BPI = FuncInfo.BPI; |
| 1996 | const BasicBlock *SrcBB = Src->getBasicBlock(); |
| 1997 | const BasicBlock *DstBB = Dst->getBasicBlock(); |
| 1998 | if (!BPI) { |
| 1999 | // If BPI is not available, set the default probability as 1 / N, where N is |
| 2000 | // the number of successors. |
| 2001 | auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); |
| 2002 | return BranchProbability(1, SuccSize); |
| 2003 | } |
| 2004 | return BPI->getEdgeProbability(SrcBB, DstBB); |
| 2005 | } |
| 2006 | |
| 2007 | void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, |
| 2008 | MachineBasicBlock *Dst, |
| 2009 | BranchProbability Prob) { |
| 2010 | if (!FuncInfo.BPI) |
| 2011 | Src->addSuccessorWithoutProb(Dst); |
| 2012 | else { |
| 2013 | if (Prob.isUnknown()) |
| 2014 | Prob = getEdgeProbability(Src, Dst); |
| 2015 | Src->addSuccessor(Dst, Prob); |
| 2016 | } |
| 2017 | } |
| 2018 | |
| 2019 | static bool InBlock(const Value *V, const BasicBlock *BB) { |
| 2020 | if (const Instruction *I = dyn_cast<Instruction>(V)) |
| 2021 | return I->getParent() == BB; |
| 2022 | return true; |
| 2023 | } |
| 2024 | |
| 2025 | /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. |
| 2026 | /// This function emits a branch and is used at the leaves of an OR or an |
| 2027 | /// AND operator tree. |
| 2028 | void |
| 2029 | SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, |
| 2030 | MachineBasicBlock *TBB, |
| 2031 | MachineBasicBlock *FBB, |
| 2032 | MachineBasicBlock *CurBB, |
| 2033 | MachineBasicBlock *SwitchBB, |
| 2034 | BranchProbability TProb, |
| 2035 | BranchProbability FProb, |
| 2036 | bool InvertCond) { |
| 2037 | const BasicBlock *BB = CurBB->getBasicBlock(); |
| 2038 | |
| 2039 | // If the leaf of the tree is a comparison, merge the condition into |
| 2040 | // the caseblock. |
| 2041 | if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { |
| 2042 | // The operands of the cmp have to be in this block. We don't know |
| 2043 | // how to export them from some other block. If this is the first block |
| 2044 | // of the sequence, no exporting is needed. |
| 2045 | if (CurBB == SwitchBB || |
| 2046 | (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && |
| 2047 | isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { |
| 2048 | ISD::CondCode Condition; |
| 2049 | if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { |
| 2050 | ICmpInst::Predicate Pred = |
| 2051 | InvertCond ? IC->getInversePredicate() : IC->getPredicate(); |
| 2052 | Condition = getICmpCondCode(Pred); |
| 2053 | } else { |
| 2054 | const FCmpInst *FC = cast<FCmpInst>(Cond); |
| 2055 | FCmpInst::Predicate Pred = |
| 2056 | InvertCond ? FC->getInversePredicate() : FC->getPredicate(); |
| 2057 | Condition = getFCmpCondCode(Pred); |
| 2058 | if (TM.Options.NoNaNsFPMath) |
| 2059 | Condition = getFCmpCodeWithoutNaN(Condition); |
| 2060 | } |
| 2061 | |
| 2062 | CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, |
| 2063 | TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); |
| 2064 | SL->SwitchCases.push_back(CB); |
| 2065 | return; |
| 2066 | } |
| 2067 | } |
| 2068 | |
| 2069 | // Create a CaseBlock record representing this branch. |
| 2070 | ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; |
| 2071 | CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), |
| 2072 | nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); |
| 2073 | SL->SwitchCases.push_back(CB); |
| 2074 | } |
| 2075 | |
| 2076 | void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, |
| 2077 | MachineBasicBlock *TBB, |
| 2078 | MachineBasicBlock *FBB, |
| 2079 | MachineBasicBlock *CurBB, |
| 2080 | MachineBasicBlock *SwitchBB, |
| 2081 | Instruction::BinaryOps Opc, |
| 2082 | BranchProbability TProb, |
| 2083 | BranchProbability FProb, |
| 2084 | bool InvertCond) { |
| 2085 | // Skip over not part of the tree and remember to invert op and operands at |
| 2086 | // next level. |
| 2087 | Value *NotCond; |
| 2088 | if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && |
| 2089 | InBlock(NotCond, CurBB->getBasicBlock())) { |
| 2090 | FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, |
| 2091 | !InvertCond); |
| 2092 | return; |
| 2093 | } |
| 2094 | |
| 2095 | const Instruction *BOp = dyn_cast<Instruction>(Cond); |
| 2096 | // Compute the effective opcode for Cond, taking into account whether it needs |
| 2097 | // to be inverted, e.g. |
| 2098 | // and (not (or A, B)), C |
| 2099 | // gets lowered as |
| 2100 | // and (and (not A, not B), C) |
| 2101 | unsigned BOpc = 0; |
| 2102 | if (BOp) { |
| 2103 | BOpc = BOp->getOpcode(); |
| 2104 | if (InvertCond) { |
| 2105 | if (BOpc == Instruction::And) |
| 2106 | BOpc = Instruction::Or; |
| 2107 | else if (BOpc == Instruction::Or) |
| 2108 | BOpc = Instruction::And; |
| 2109 | } |
| 2110 | } |
| 2111 | |
| 2112 | // If this node is not part of the or/and tree, emit it as a branch. |
| 2113 | if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || |
| 2114 | BOpc != unsigned(Opc) || !BOp->hasOneUse() || |
| 2115 | BOp->getParent() != CurBB->getBasicBlock() || |
| 2116 | !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || |
| 2117 | !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { |
| 2118 | EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, |
| 2119 | TProb, FProb, InvertCond); |
| 2120 | return; |
| 2121 | } |
| 2122 | |
| 2123 | // Create TmpBB after CurBB. |
| 2124 | MachineFunction::iterator BBI(CurBB); |
| 2125 | MachineFunction &MF = DAG.getMachineFunction(); |
| 2126 | MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); |
| 2127 | CurBB->getParent()->insert(++BBI, TmpBB); |
| 2128 | |
| 2129 | if (Opc == Instruction::Or) { |
| 2130 | // Codegen X | Y as: |
| 2131 | // BB1: |
| 2132 | // jmp_if_X TBB |
| 2133 | // jmp TmpBB |
| 2134 | // TmpBB: |
| 2135 | // jmp_if_Y TBB |
| 2136 | // jmp FBB |
| 2137 | // |
| 2138 | |
| 2139 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 2140 | // The requirement is that |
| 2141 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
| 2142 | // = TrueProb for original BB. |
| 2143 | // Assuming the original probabilities are A and B, one choice is to set |
| 2144 | // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to |
| 2145 | // A/(1+B) and 2B/(1+B). This choice assumes that |
| 2146 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 2147 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 2148 | // TmpBB, but the math is more complicated. |
| 2149 | |
| 2150 | auto NewTrueProb = TProb / 2; |
| 2151 | auto NewFalseProb = TProb / 2 + FProb; |
| 2152 | // Emit the LHS condition. |
| 2153 | FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, |
| 2154 | NewTrueProb, NewFalseProb, InvertCond); |
| 2155 | |
| 2156 | // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). |
| 2157 | SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; |
| 2158 | BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); |
| 2159 | // Emit the RHS condition into TmpBB. |
| 2160 | FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, |
| 2161 | Probs[0], Probs[1], InvertCond); |
| 2162 | } else { |
| 2163 | assert(Opc == Instruction::And && "Unknown merge op!" ); |
| 2164 | // Codegen X & Y as: |
| 2165 | // BB1: |
| 2166 | // jmp_if_X TmpBB |
| 2167 | // jmp FBB |
| 2168 | // TmpBB: |
| 2169 | // jmp_if_Y TBB |
| 2170 | // jmp FBB |
| 2171 | // |
| 2172 | // This requires creation of TmpBB after CurBB. |
| 2173 | |
| 2174 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 2175 | // The requirement is that |
| 2176 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
| 2177 | // = FalseProb for original BB. |
| 2178 | // Assuming the original probabilities are A and B, one choice is to set |
| 2179 | // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to |
| 2180 | // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == |
| 2181 | // TrueProb for BB1 * FalseProb for TmpBB. |
| 2182 | |
| 2183 | auto NewTrueProb = TProb + FProb / 2; |
| 2184 | auto NewFalseProb = FProb / 2; |
| 2185 | // Emit the LHS condition. |
| 2186 | FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, |
| 2187 | NewTrueProb, NewFalseProb, InvertCond); |
| 2188 | |
| 2189 | // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). |
| 2190 | SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; |
| 2191 | BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); |
| 2192 | // Emit the RHS condition into TmpBB. |
| 2193 | FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, |
| 2194 | Probs[0], Probs[1], InvertCond); |
| 2195 | } |
| 2196 | } |
| 2197 | |
| 2198 | /// If the set of cases should be emitted as a series of branches, return true. |
| 2199 | /// If we should emit this as a bunch of and/or'd together conditions, return |
| 2200 | /// false. |
| 2201 | bool |
| 2202 | SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { |
| 2203 | if (Cases.size() != 2) return true; |
| 2204 | |
| 2205 | // If this is two comparisons of the same values or'd or and'd together, they |
| 2206 | // will get folded into a single comparison, so don't emit two blocks. |
| 2207 | if ((Cases[0].CmpLHS == Cases[1].CmpLHS && |
| 2208 | Cases[0].CmpRHS == Cases[1].CmpRHS) || |
| 2209 | (Cases[0].CmpRHS == Cases[1].CmpLHS && |
| 2210 | Cases[0].CmpLHS == Cases[1].CmpRHS)) { |
| 2211 | return false; |
| 2212 | } |
| 2213 | |
| 2214 | // Handle: (X != null) | (Y != null) --> (X|Y) != 0 |
| 2215 | // Handle: (X == null) & (Y == null) --> (X|Y) == 0 |
| 2216 | if (Cases[0].CmpRHS == Cases[1].CmpRHS && |
| 2217 | Cases[0].CC == Cases[1].CC && |
| 2218 | isa<Constant>(Cases[0].CmpRHS) && |
| 2219 | cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { |
| 2220 | if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) |
| 2221 | return false; |
| 2222 | if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) |
| 2223 | return false; |
| 2224 | } |
| 2225 | |
| 2226 | return true; |
| 2227 | } |
| 2228 | |
| 2229 | void SelectionDAGBuilder::visitBr(const BranchInst &I) { |
| 2230 | MachineBasicBlock *BrMBB = FuncInfo.MBB; |
| 2231 | |
| 2232 | // Update machine-CFG edges. |
| 2233 | MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; |
| 2234 | |
| 2235 | if (I.isUnconditional()) { |
| 2236 | // Update machine-CFG edges. |
| 2237 | BrMBB->addSuccessor(Succ0MBB); |
| 2238 | |
| 2239 | // If this is not a fall-through branch or optimizations are switched off, |
| 2240 | // emit the branch. |
| 2241 | if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) |
| 2242 | DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), |
| 2243 | MVT::Other, getControlRoot(), |
| 2244 | DAG.getBasicBlock(Succ0MBB))); |
| 2245 | |
| 2246 | return; |
| 2247 | } |
| 2248 | |
| 2249 | // If this condition is one of the special cases we handle, do special stuff |
| 2250 | // now. |
| 2251 | const Value *CondVal = I.getCondition(); |
| 2252 | MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; |
| 2253 | |
| 2254 | // If this is a series of conditions that are or'd or and'd together, emit |
| 2255 | // this as a sequence of branches instead of setcc's with and/or operations. |
| 2256 | // As long as jumps are not expensive, this should improve performance. |
| 2257 | // For example, instead of something like: |
| 2258 | // cmp A, B |
| 2259 | // C = seteq |
| 2260 | // cmp D, E |
| 2261 | // F = setle |
| 2262 | // or C, F |
| 2263 | // jnz foo |
| 2264 | // Emit: |
| 2265 | // cmp A, B |
| 2266 | // je foo |
| 2267 | // cmp D, E |
| 2268 | // jle foo |
| 2269 | if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { |
| 2270 | Instruction::BinaryOps Opcode = BOp->getOpcode(); |
| 2271 | if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && |
| 2272 | !I.getMetadata(LLVMContext::MD_unpredictable) && |
| 2273 | (Opcode == Instruction::And || Opcode == Instruction::Or)) { |
| 2274 | FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, |
| 2275 | Opcode, |
| 2276 | getEdgeProbability(BrMBB, Succ0MBB), |
| 2277 | getEdgeProbability(BrMBB, Succ1MBB), |
| 2278 | /*InvertCond=*/false); |
| 2279 | // If the compares in later blocks need to use values not currently |
| 2280 | // exported from this block, export them now. This block should always |
| 2281 | // be the first entry. |
| 2282 | assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!" ); |
| 2283 | |
| 2284 | // Allow some cases to be rejected. |
| 2285 | if (ShouldEmitAsBranches(SL->SwitchCases)) { |
| 2286 | for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { |
| 2287 | ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); |
| 2288 | ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); |
| 2289 | } |
| 2290 | |
| 2291 | // Emit the branch for this block. |
| 2292 | visitSwitchCase(SL->SwitchCases[0], BrMBB); |
| 2293 | SL->SwitchCases.erase(SL->SwitchCases.begin()); |
| 2294 | return; |
| 2295 | } |
| 2296 | |
| 2297 | // Okay, we decided not to do this, remove any inserted MBB's and clear |
| 2298 | // SwitchCases. |
| 2299 | for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) |
| 2300 | FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); |
| 2301 | |
| 2302 | SL->SwitchCases.clear(); |
| 2303 | } |
| 2304 | } |
| 2305 | |
| 2306 | // Create a CaseBlock record representing this branch. |
| 2307 | CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), |
| 2308 | nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); |
| 2309 | |
| 2310 | // Use visitSwitchCase to actually insert the fast branch sequence for this |
| 2311 | // cond branch. |
| 2312 | visitSwitchCase(CB, BrMBB); |
| 2313 | } |
| 2314 | |
| 2315 | /// visitSwitchCase - Emits the necessary code to represent a single node in |
| 2316 | /// the binary search tree resulting from lowering a switch instruction. |
| 2317 | void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, |
| 2318 | MachineBasicBlock *SwitchBB) { |
| 2319 | SDValue Cond; |
| 2320 | SDValue CondLHS = getValue(CB.CmpLHS); |
| 2321 | SDLoc dl = CB.DL; |
| 2322 | |
| 2323 | if (CB.CC == ISD::SETTRUE) { |
| 2324 | // Branch or fall through to TrueBB. |
| 2325 | addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); |
| 2326 | SwitchBB->normalizeSuccProbs(); |
| 2327 | if (CB.TrueBB != NextBlock(SwitchBB)) { |
| 2328 | DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), |
| 2329 | DAG.getBasicBlock(CB.TrueBB))); |
| 2330 | } |
| 2331 | return; |
| 2332 | } |
| 2333 | |
| 2334 | auto &TLI = DAG.getTargetLoweringInfo(); |
| 2335 | EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); |
| 2336 | |
| 2337 | // Build the setcc now. |
| 2338 | if (!CB.CmpMHS) { |
| 2339 | // Fold "(X == true)" to X and "(X == false)" to !X to |
| 2340 | // handle common cases produced by branch lowering. |
| 2341 | if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && |
| 2342 | CB.CC == ISD::SETEQ) |
| 2343 | Cond = CondLHS; |
| 2344 | else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && |
| 2345 | CB.CC == ISD::SETEQ) { |
| 2346 | SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); |
| 2347 | Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); |
| 2348 | } else { |
| 2349 | SDValue CondRHS = getValue(CB.CmpRHS); |
| 2350 | |
| 2351 | // If a pointer's DAG type is larger than its memory type then the DAG |
| 2352 | // values are zero-extended. This breaks signed comparisons so truncate |
| 2353 | // back to the underlying type before doing the compare. |
| 2354 | if (CondLHS.getValueType() != MemVT) { |
| 2355 | CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); |
| 2356 | CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); |
| 2357 | } |
| 2358 | Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); |
| 2359 | } |
| 2360 | } else { |
| 2361 | assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now" ); |
| 2362 | |
| 2363 | const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); |
| 2364 | const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); |
| 2365 | |
| 2366 | SDValue CmpOp = getValue(CB.CmpMHS); |
| 2367 | EVT VT = CmpOp.getValueType(); |
| 2368 | |
| 2369 | if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { |
| 2370 | Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), |
| 2371 | ISD::SETLE); |
| 2372 | } else { |
| 2373 | SDValue SUB = DAG.getNode(ISD::SUB, dl, |
| 2374 | VT, CmpOp, DAG.getConstant(Low, dl, VT)); |
| 2375 | Cond = DAG.getSetCC(dl, MVT::i1, SUB, |
| 2376 | DAG.getConstant(High-Low, dl, VT), ISD::SETULE); |
| 2377 | } |
| 2378 | } |
| 2379 | |
| 2380 | // Update successor info |
| 2381 | addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); |
| 2382 | // TrueBB and FalseBB are always different unless the incoming IR is |
| 2383 | // degenerate. This only happens when running llc on weird IR. |
| 2384 | if (CB.TrueBB != CB.FalseBB) |
| 2385 | addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); |
| 2386 | SwitchBB->normalizeSuccProbs(); |
| 2387 | |
| 2388 | // If the lhs block is the next block, invert the condition so that we can |
| 2389 | // fall through to the lhs instead of the rhs block. |
| 2390 | if (CB.TrueBB == NextBlock(SwitchBB)) { |
| 2391 | std::swap(CB.TrueBB, CB.FalseBB); |
| 2392 | SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); |
| 2393 | Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); |
| 2394 | } |
| 2395 | |
| 2396 | SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, |
| 2397 | MVT::Other, getControlRoot(), Cond, |
| 2398 | DAG.getBasicBlock(CB.TrueBB)); |
| 2399 | |
| 2400 | // Insert the false branch. Do this even if it's a fall through branch, |
| 2401 | // this makes it easier to do DAG optimizations which require inverting |
| 2402 | // the branch condition. |
| 2403 | BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, |
| 2404 | DAG.getBasicBlock(CB.FalseBB)); |
| 2405 | |
| 2406 | DAG.setRoot(BrCond); |
| 2407 | } |
| 2408 | |
| 2409 | /// visitJumpTable - Emit JumpTable node in the current MBB |
| 2410 | void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { |
| 2411 | // Emit the code for the jump table |
| 2412 | assert(JT.Reg != -1U && "Should lower JT Header first!" ); |
| 2413 | const DataLayout &TD = DAG.getDataLayout(); |
| 2414 | const auto &TLI = DAG.getTargetLoweringInfo(); |
| 2415 | EVT PTy = TLI.getPointerTy(TD, TD.getGlobalsAddressSpace()); |
| 2416 | EVT IndexTy = TLI.getPointerRangeTy(TD , TD.getProgramAddressSpace()); |
| 2417 | SDValue Index = |
| 2418 | DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), JT.Reg, IndexTy); |
| 2419 | SDValue Table = DAG.getJumpTable(JT.JTI, PTy); |
| 2420 | SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), MVT::Other, |
| 2421 | Index.getValue(1), Table, Index); |
| 2422 | assert(BrJumpTable->getOperand(2).getValueType().isInteger()); |
| 2423 | DAG.setRoot(BrJumpTable); |
| 2424 | } |
| 2425 | |
| 2426 | /// visitJumpTableHeader - This function emits necessary code to produce index |
| 2427 | /// in the JumpTable from switch case. |
| 2428 | void SelectionDAGBuilder::(SwitchCG::JumpTable &JT, |
| 2429 | JumpTableHeader &JTH, |
| 2430 | MachineBasicBlock *SwitchBB) { |
| 2431 | SDLoc dl = getCurSDLoc(); |
| 2432 | |
| 2433 | // Subtract the lowest switch case value from the value being switched on. |
| 2434 | SDValue SwitchOp = getValue(JTH.SValue); |
| 2435 | EVT VT = SwitchOp.getValueType(); |
| 2436 | SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, |
| 2437 | DAG.getConstant(JTH.First, dl, VT)); |
| 2438 | |
| 2439 | // The SDNode we just created, which holds the value being switched on minus |
| 2440 | // the smallest case value, needs to be copied to a virtual register so it |
| 2441 | // can be used as an index into the jump table in a subsequent basic block. |
| 2442 | // This value may be smaller or larger than the target's pointer type, and |
| 2443 | // therefore require extension or truncating. |
| 2444 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 2445 | SwitchOp = |
| 2446 | DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerRangeTy(DAG.getDataLayout())); |
| 2447 | |
| 2448 | unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerRangeTy(DAG.getDataLayout())); |
| 2449 | SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, |
| 2450 | JumpTableReg, SwitchOp); |
| 2451 | JT.Reg = JumpTableReg; |
| 2452 | |
| 2453 | if (!JTH.OmitRangeCheck) { |
| 2454 | // Emit the range check for the jump table, and branch to the default block |
| 2455 | // for the switch statement if the value being switched on exceeds the |
| 2456 | // largest case in the switch. |
| 2457 | SDValue CMP = DAG.getSetCC( |
| 2458 | dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), |
| 2459 | Sub.getValueType()), |
| 2460 | Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); |
| 2461 | |
| 2462 | SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, |
| 2463 | MVT::Other, CopyTo, CMP, |
| 2464 | DAG.getBasicBlock(JT.Default)); |
| 2465 | |
| 2466 | // Avoid emitting unnecessary branches to the next block. |
| 2467 | if (JT.MBB != NextBlock(SwitchBB)) |
| 2468 | BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, |
| 2469 | DAG.getBasicBlock(JT.MBB)); |
| 2470 | |
| 2471 | DAG.setRoot(BrCond); |
| 2472 | } else { |
| 2473 | // Avoid emitting unnecessary branches to the next block. |
| 2474 | if (JT.MBB != NextBlock(SwitchBB)) |
| 2475 | DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, |
| 2476 | DAG.getBasicBlock(JT.MBB))); |
| 2477 | else |
| 2478 | DAG.setRoot(CopyTo); |
| 2479 | } |
| 2480 | } |
| 2481 | |
| 2482 | /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global |
| 2483 | /// variable if there exists one. |
| 2484 | static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, |
| 2485 | SDValue &Chain) { |
| 2486 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 2487 | EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), |
| 2488 | DAG.getDataLayout().getAllocaAddrSpace()); |
| 2489 | EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), |
| 2490 | DAG.getDataLayout().getAllocaAddrSpace()); |
| 2491 | MachineFunction &MF = DAG.getMachineFunction(); |
| 2492 | Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); |
| 2493 | MachineSDNode *Node = |
| 2494 | DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); |
| 2495 | if (Global) { |
| 2496 | MachinePointerInfo MPInfo(Global); |
| 2497 | auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | |
| 2498 | MachineMemOperand::MODereferenceable; |
| 2499 | MachineMemOperand *MemRef = MF.getMachineMemOperand( |
| 2500 | MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); |
| 2501 | DAG.setNodeMemRefs(Node, {MemRef}); |
| 2502 | } |
| 2503 | if (PtrTy != PtrMemTy) |
| 2504 | return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); |
| 2505 | return SDValue(Node, 0); |
| 2506 | } |
| 2507 | |
| 2508 | /// Codegen a new tail for a stack protector check ParentMBB which has had its |
| 2509 | /// tail spliced into a stack protector check success bb. |
| 2510 | /// |
| 2511 | /// For a high level explanation of how this fits into the stack protector |
| 2512 | /// generation see the comment on the declaration of class |
| 2513 | /// StackProtectorDescriptor. |
| 2514 | void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, |
| 2515 | MachineBasicBlock *ParentBB) { |
| 2516 | |
| 2517 | // First create the loads to the guard/stack slot for the comparison. |
| 2518 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 2519 | EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), |
| 2520 | DAG.getDataLayout().getAllocaAddrSpace()); |
| 2521 | EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), |
| 2522 | DAG.getDataLayout().getAllocaAddrSpace()); |
| 2523 | |
| 2524 | MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); |
| 2525 | int FI = MFI.getStackProtectorIndex(); |
| 2526 | |
| 2527 | SDValue Guard; |
| 2528 | SDLoc dl = getCurSDLoc(); |
| 2529 | SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); |
| 2530 | const Module &M = *ParentBB->getParent()->getFunction().getParent(); |
| 2531 | unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); |
| 2532 | |
| 2533 | // Generate code to load the content of the guard slot. |
| 2534 | SDValue GuardVal = DAG.getLoad( |
| 2535 | PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, |
| 2536 | MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, |
| 2537 | MachineMemOperand::MOVolatile); |
| 2538 | |
| 2539 | if (TLI.useStackGuardXorFP()) |
| 2540 | GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); |
| 2541 | |
| 2542 | // Retrieve guard check function, nullptr if instrumentation is inlined. |
| 2543 | if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { |
| 2544 | // The target provides a guard check function to validate the guard value. |
| 2545 | // Generate a call to that function with the content of the guard slot as |
| 2546 | // argument. |
| 2547 | FunctionType *FnTy = GuardCheckFn->getFunctionType(); |
| 2548 | assert(FnTy->getNumParams() == 1 && "Invalid function signature" ); |
| 2549 | |
| 2550 | TargetLowering::ArgListTy Args; |
| 2551 | TargetLowering::ArgListEntry Entry; |
| 2552 | Entry.Node = GuardVal; |
| 2553 | Entry.Ty = FnTy->getParamType(0); |
| 2554 | if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) |
| 2555 | Entry.IsInReg = true; |
| 2556 | Args.push_back(Entry); |
| 2557 | |
| 2558 | TargetLowering::CallLoweringInfo CLI(DAG); |
| 2559 | CLI.setDebugLoc(getCurSDLoc()) |
| 2560 | .setChain(DAG.getEntryNode()) |
| 2561 | .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), |
| 2562 | getValue(GuardCheckFn), std::move(Args)); |
| 2563 | |
| 2564 | std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); |
| 2565 | DAG.setRoot(Result.second); |
| 2566 | return; |
| 2567 | } |
| 2568 | |
| 2569 | // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. |
| 2570 | // Otherwise, emit a volatile load to retrieve the stack guard value. |
| 2571 | SDValue Chain = DAG.getEntryNode(); |
| 2572 | if (TLI.useLoadStackGuardNode()) { |
| 2573 | Guard = getLoadStackGuard(DAG, dl, Chain); |
| 2574 | } else { |
| 2575 | const Value *IRGuard = TLI.getSDagStackGuard(M); |
| 2576 | SDValue GuardPtr = getValue(IRGuard); |
| 2577 | |
| 2578 | Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, |
| 2579 | MachinePointerInfo(IRGuard, 0), Align, |
| 2580 | MachineMemOperand::MOVolatile); |
| 2581 | } |
| 2582 | |
| 2583 | // Perform the comparison via a subtract/getsetcc. |
| 2584 | EVT VT = Guard.getValueType(); |
| 2585 | SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); |
| 2586 | |
| 2587 | SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), |
| 2588 | *DAG.getContext(), |
| 2589 | Sub.getValueType()), |
| 2590 | Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); |
| 2591 | |
| 2592 | // If the sub is not 0, then we know the guard/stackslot do not equal, so |
| 2593 | // branch to failure MBB. |
| 2594 | SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, |
| 2595 | MVT::Other, GuardVal.getOperand(0), |
| 2596 | Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); |
| 2597 | // Otherwise branch to success MBB. |
| 2598 | SDValue Br = DAG.getNode(ISD::BR, dl, |
| 2599 | MVT::Other, BrCond, |
| 2600 | DAG.getBasicBlock(SPD.getSuccessMBB())); |
| 2601 | |
| 2602 | DAG.setRoot(Br); |
| 2603 | } |
| 2604 | |
| 2605 | /// Codegen the failure basic block for a stack protector check. |
| 2606 | /// |
| 2607 | /// A failure stack protector machine basic block consists simply of a call to |
| 2608 | /// __stack_chk_fail(). |
| 2609 | /// |
| 2610 | /// For a high level explanation of how this fits into the stack protector |
| 2611 | /// generation see the comment on the declaration of class |
| 2612 | /// StackProtectorDescriptor. |
| 2613 | void |
| 2614 | SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { |
| 2615 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 2616 | SDValue Chain = |
| 2617 | TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, |
| 2618 | None, false, getCurSDLoc(), false, false).second; |
| 2619 | // On PS4, the "return address" must still be within the calling function, |
| 2620 | // even if it's at the very end, so emit an explicit TRAP here. |
| 2621 | // Passing 'true' for doesNotReturn above won't generate the trap for us. |
| 2622 | if (TM.getTargetTriple().isPS4CPU()) |
| 2623 | Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); |
| 2624 | |
| 2625 | DAG.setRoot(Chain); |
| 2626 | } |
| 2627 | |
| 2628 | /// visitBitTestHeader - This function emits necessary code to produce value |
| 2629 | /// suitable for "bit tests" |
| 2630 | void SelectionDAGBuilder::(BitTestBlock &B, |
| 2631 | MachineBasicBlock *SwitchBB) { |
| 2632 | SDLoc dl = getCurSDLoc(); |
| 2633 | |
| 2634 | // Subtract the minimum value |
| 2635 | SDValue SwitchOp = getValue(B.SValue); |
| 2636 | EVT VT = SwitchOp.getValueType(); |
| 2637 | SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, |
| 2638 | DAG.getConstant(B.First, dl, VT)); |
| 2639 | |
| 2640 | // Check range |
| 2641 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 2642 | SDValue RangeCmp = DAG.getSetCC( |
| 2643 | dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), |
| 2644 | Sub.getValueType()), |
| 2645 | Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); |
| 2646 | |
| 2647 | // Determine the type of the test operands. |
| 2648 | bool UsePtrType = false; |
| 2649 | if (!TLI.isTypeLegal(VT)) |
| 2650 | UsePtrType = true; |
| 2651 | else { |
| 2652 | for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) |
| 2653 | if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { |
| 2654 | // Switch table case range are encoded into series of masks. |
| 2655 | // Just use pointer type, it's guaranteed to fit. |
| 2656 | UsePtrType = true; |
| 2657 | break; |
| 2658 | } |
| 2659 | } |
| 2660 | if (UsePtrType) { |
| 2661 | VT = TLI.getPointerTy(DAG.getDataLayout(), 0); // FIXME: AS0 ok? |
| 2662 | Sub = DAG.getZExtOrTrunc(Sub, dl, VT); |
| 2663 | } |
| 2664 | |
| 2665 | B.RegVT = VT.getSimpleVT(); |
| 2666 | B.Reg = FuncInfo.CreateReg(B.RegVT); |
| 2667 | SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); |
| 2668 | |
| 2669 | MachineBasicBlock* MBB = B.Cases[0].ThisBB; |
| 2670 | |
| 2671 | addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); |
| 2672 | addSuccessorWithProb(SwitchBB, MBB, B.Prob); |
| 2673 | SwitchBB->normalizeSuccProbs(); |
| 2674 | |
| 2675 | SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, |
| 2676 | MVT::Other, CopyTo, RangeCmp, |
| 2677 | DAG.getBasicBlock(B.Default)); |
| 2678 | |
| 2679 | // Avoid emitting unnecessary branches to the next block. |
| 2680 | if (MBB != NextBlock(SwitchBB)) |
| 2681 | BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, |
| 2682 | DAG.getBasicBlock(MBB)); |
| 2683 | |
| 2684 | DAG.setRoot(BrRange); |
| 2685 | } |
| 2686 | |
| 2687 | /// visitBitTestCase - this function produces one "bit test" |
| 2688 | void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, |
| 2689 | MachineBasicBlock* NextMBB, |
| 2690 | BranchProbability BranchProbToNext, |
| 2691 | unsigned Reg, |
| 2692 | BitTestCase &B, |
| 2693 | MachineBasicBlock *SwitchBB) { |
| 2694 | SDLoc dl = getCurSDLoc(); |
| 2695 | MVT VT = BB.RegVT; |
| 2696 | SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); |
| 2697 | SDValue Cmp; |
| 2698 | unsigned PopCount = countPopulation(B.Mask); |
| 2699 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 2700 | if (PopCount == 1) { |
| 2701 | // Testing for a single bit; just compare the shift count with what it |
| 2702 | // would need to be to shift a 1 bit in that position. |
| 2703 | Cmp = DAG.getSetCC( |
| 2704 | dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), |
| 2705 | ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), |
| 2706 | ISD::SETEQ); |
| 2707 | } else if (PopCount == BB.Range) { |
| 2708 | // There is only one zero bit in the range, test for it directly. |
| 2709 | Cmp = DAG.getSetCC( |
| 2710 | dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), |
| 2711 | ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), |
| 2712 | ISD::SETNE); |
| 2713 | } else { |
| 2714 | // Make desired shift |
| 2715 | SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, |
| 2716 | DAG.getConstant(1, dl, VT), ShiftOp); |
| 2717 | |
| 2718 | // Emit bit tests and jumps |
| 2719 | SDValue AndOp = DAG.getNode(ISD::AND, dl, |
| 2720 | VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); |
| 2721 | Cmp = DAG.getSetCC( |
| 2722 | dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), |
| 2723 | AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); |
| 2724 | } |
| 2725 | |
| 2726 | // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. |
| 2727 | addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); |
| 2728 | // The branch probability from SwitchBB to NextMBB is BranchProbToNext. |
| 2729 | addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); |
| 2730 | // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is |
| 2731 | // one as they are relative probabilities (and thus work more like weights), |
| 2732 | // and hence we need to normalize them to let the sum of them become one. |
| 2733 | SwitchBB->normalizeSuccProbs(); |
| 2734 | |
| 2735 | SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, |
| 2736 | MVT::Other, getControlRoot(), |
| 2737 | Cmp, DAG.getBasicBlock(B.TargetBB)); |
| 2738 | |
| 2739 | // Avoid emitting unnecessary branches to the next block. |
| 2740 | if (NextMBB != NextBlock(SwitchBB)) |
| 2741 | BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, |
| 2742 | DAG.getBasicBlock(NextMBB)); |
| 2743 | |
| 2744 | DAG.setRoot(BrAnd); |
| 2745 | } |
| 2746 | |
| 2747 | void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { |
| 2748 | MachineBasicBlock *InvokeMBB = FuncInfo.MBB; |
| 2749 | |
| 2750 | // Retrieve successors. Look through artificial IR level blocks like |
| 2751 | // catchswitch for successors. |
| 2752 | MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; |
| 2753 | const BasicBlock *EHPadBB = I.getSuccessor(1); |
| 2754 | |
| 2755 | // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't |
| 2756 | // have to do anything here to lower funclet bundles. |
| 2757 | assert(!I.hasOperandBundlesOtherThan( |
| 2758 | {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && |
| 2759 | "Cannot lower invokes with arbitrary operand bundles yet!" ); |
| 2760 | |
| 2761 | const Value *Callee(I.getCalledValue()); |
| 2762 | const Function *Fn = dyn_cast<Function>(Callee); |
| 2763 | if (isa<InlineAsm>(Callee)) |
| 2764 | visitInlineAsm(&I); |
| 2765 | else if (Fn && Fn->isIntrinsic()) { |
| 2766 | switch (Fn->getIntrinsicID()) { |
| 2767 | default: |
| 2768 | llvm_unreachable("Cannot invoke this intrinsic" ); |
| 2769 | case Intrinsic::donothing: |
| 2770 | // Ignore invokes to @llvm.donothing: jump directly to the next BB. |
| 2771 | break; |
| 2772 | case Intrinsic::experimental_patchpoint_void: |
| 2773 | case Intrinsic::experimental_patchpoint_i64: |
| 2774 | visitPatchpoint(&I, EHPadBB); |
| 2775 | break; |
| 2776 | case Intrinsic::experimental_gc_statepoint: |
| 2777 | LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); |
| 2778 | break; |
| 2779 | case Intrinsic::wasm_rethrow_in_catch: { |
| 2780 | // This is usually done in visitTargetIntrinsic, but this intrinsic is |
| 2781 | // special because it can be invoked, so we manually lower it to a DAG |
| 2782 | // node here. |
| 2783 | SmallVector<SDValue, 8> Ops; |
| 2784 | Ops.push_back(getRoot()); // inchain |
| 2785 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 2786 | Ops.push_back( |
| 2787 | DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), |
| 2788 | TLI.getPointerTy(DAG.getDataLayout(), TLI.getExceptionPointerAS()))); |
| 2789 | SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain |
| 2790 | DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); |
| 2791 | break; |
| 2792 | } |
| 2793 | } |
| 2794 | } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { |
| 2795 | // Currently we do not lower any intrinsic calls with deopt operand bundles. |
| 2796 | // Eventually we will support lowering the @llvm.experimental.deoptimize |
| 2797 | // intrinsic, and right now there are no plans to support other intrinsics |
| 2798 | // with deopt state. |
| 2799 | LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); |
| 2800 | } else { |
| 2801 | LowerCallTo(&I, getValue(Callee), false, EHPadBB); |
| 2802 | } |
| 2803 | |
| 2804 | // If the value of the invoke is used outside of its defining block, make it |
| 2805 | // available as a virtual register. |
| 2806 | // We already took care of the exported value for the statepoint instruction |
| 2807 | // during call to the LowerStatepoint. |
| 2808 | if (!isStatepoint(I)) { |
| 2809 | CopyToExportRegsIfNeeded(&I); |
| 2810 | } |
| 2811 | |
| 2812 | SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; |
| 2813 | BranchProbabilityInfo *BPI = FuncInfo.BPI; |
| 2814 | BranchProbability EHPadBBProb = |
| 2815 | BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) |
| 2816 | : BranchProbability::getZero(); |
| 2817 | findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); |
| 2818 | |
| 2819 | // Update successor info. |
| 2820 | addSuccessorWithProb(InvokeMBB, Return); |
| 2821 | for (auto &UnwindDest : UnwindDests) { |
| 2822 | UnwindDest.first->setIsEHPad(); |
| 2823 | addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); |
| 2824 | } |
| 2825 | InvokeMBB->normalizeSuccProbs(); |
| 2826 | |
| 2827 | // Drop into normal successor. |
| 2828 | DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), |
| 2829 | DAG.getBasicBlock(Return))); |
| 2830 | } |
| 2831 | |
| 2832 | void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { |
| 2833 | MachineBasicBlock *CallBrMBB = FuncInfo.MBB; |
| 2834 | |
| 2835 | // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't |
| 2836 | // have to do anything here to lower funclet bundles. |
| 2837 | assert(!I.hasOperandBundlesOtherThan( |
| 2838 | {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && |
| 2839 | "Cannot lower callbrs with arbitrary operand bundles yet!" ); |
| 2840 | |
| 2841 | assert(isa<InlineAsm>(I.getCalledValue()) && |
| 2842 | "Only know how to handle inlineasm callbr" ); |
| 2843 | visitInlineAsm(&I); |
| 2844 | |
| 2845 | // Retrieve successors. |
| 2846 | MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; |
| 2847 | |
| 2848 | // Update successor info. |
| 2849 | addSuccessorWithProb(CallBrMBB, Return); |
| 2850 | for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { |
| 2851 | MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; |
| 2852 | addSuccessorWithProb(CallBrMBB, Target); |
| 2853 | } |
| 2854 | CallBrMBB->normalizeSuccProbs(); |
| 2855 | |
| 2856 | // Drop into default successor. |
| 2857 | DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), |
| 2858 | MVT::Other, getControlRoot(), |
| 2859 | DAG.getBasicBlock(Return))); |
| 2860 | } |
| 2861 | |
| 2862 | void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { |
| 2863 | llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!" ); |
| 2864 | } |
| 2865 | |
| 2866 | void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { |
| 2867 | assert(FuncInfo.MBB->isEHPad() && |
| 2868 | "Call to landingpad not in landing pad!" ); |
| 2869 | |
| 2870 | // If there aren't registers to copy the values into (e.g., during SjLj |
| 2871 | // exceptions), then don't bother to create these DAG nodes. |
| 2872 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 2873 | const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); |
| 2874 | if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && |
| 2875 | TLI.getExceptionSelectorRegister(PersonalityFn) == 0) |
| 2876 | return; |
| 2877 | |
| 2878 | // If landingpad's return type is token type, we don't create DAG nodes |
| 2879 | // for its exception pointer and selector value. The extraction of exception |
| 2880 | // pointer or selector value from token type landingpads is not currently |
| 2881 | // supported. |
| 2882 | if (LP.getType()->isTokenTy()) |
| 2883 | return; |
| 2884 | |
| 2885 | SmallVector<EVT, 2> ValueVTs; |
| 2886 | SDLoc dl = getCurSDLoc(); |
| 2887 | ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); |
| 2888 | assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported" ); |
| 2889 | |
| 2890 | // Get the two live-in registers as SDValues. The physregs have already been |
| 2891 | // copied into virtual registers. |
| 2892 | SDValue Ops[2]; |
| 2893 | if (FuncInfo.ExceptionPointerVirtReg) { |
| 2894 | SDValue EPtr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, |
| 2895 | FuncInfo.ExceptionPointerVirtReg, |
| 2896 | TLI.getPointerTy(DAG.getDataLayout(), |
| 2897 | TLI.getExceptionPointerAS())); |
| 2898 | Ops[0] = (EPtr.getValueType().isFatPointer()) ? EPtr : |
| 2899 | DAG.getZExtOrTrunc(EPtr, dl, ValueVTs[0]); |
| 2900 | } else { |
| 2901 | Ops[0] = DAG.getConstant( |
| 2902 | 0, dl, |
| 2903 | TLI.getPointerTy(DAG.getDataLayout(), TLI.getExceptionPointerAS())); |
| 2904 | } |
| 2905 | Ops[1] = DAG.getZExtOrTrunc( |
| 2906 | DAG.getCopyFromReg(DAG.getEntryNode(), dl, |
| 2907 | FuncInfo.ExceptionSelectorVirtReg, |
| 2908 | TLI.getPointerRangeTy(DAG.getDataLayout())), |
| 2909 | dl, ValueVTs[1]); |
| 2910 | |
| 2911 | // Merge into one. |
| 2912 | SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, |
| 2913 | DAG.getVTList(ValueVTs), Ops); |
| 2914 | setValue(&LP, Res); |
| 2915 | } |
| 2916 | |
| 2917 | void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, |
| 2918 | MachineBasicBlock *Last) { |
| 2919 | // Update JTCases. |
| 2920 | for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) |
| 2921 | if (SL->JTCases[i].first.HeaderBB == First) |
| 2922 | SL->JTCases[i].first.HeaderBB = Last; |
| 2923 | |
| 2924 | // Update BitTestCases. |
| 2925 | for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) |
| 2926 | if (SL->BitTestCases[i].Parent == First) |
| 2927 | SL->BitTestCases[i].Parent = Last; |
| 2928 | } |
| 2929 | |
| 2930 | void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { |
| 2931 | MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; |
| 2932 | |
| 2933 | // Update machine-CFG edges with unique successors. |
| 2934 | SmallSet<BasicBlock*, 32> Done; |
| 2935 | for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { |
| 2936 | BasicBlock *BB = I.getSuccessor(i); |
| 2937 | bool Inserted = Done.insert(BB).second; |
| 2938 | if (!Inserted) |
| 2939 | continue; |
| 2940 | |
| 2941 | MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; |
| 2942 | addSuccessorWithProb(IndirectBrMBB, Succ); |
| 2943 | } |
| 2944 | IndirectBrMBB->normalizeSuccProbs(); |
| 2945 | |
| 2946 | DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), |
| 2947 | MVT::Other, getControlRoot(), |
| 2948 | getValue(I.getAddress()))); |
| 2949 | } |
| 2950 | |
| 2951 | void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { |
| 2952 | if (!DAG.getTarget().Options.TrapUnreachable) |
| 2953 | return; |
| 2954 | |
| 2955 | // We may be able to ignore unreachable behind a noreturn call. |
| 2956 | if (DAG.getTarget().Options.NoTrapAfterNoreturn) { |
| 2957 | const BasicBlock &BB = *I.getParent(); |
| 2958 | if (&I != &BB.front()) { |
| 2959 | BasicBlock::const_iterator PredI = |
| 2960 | std::prev(BasicBlock::const_iterator(&I)); |
| 2961 | if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { |
| 2962 | if (Call->doesNotReturn()) |
| 2963 | return; |
| 2964 | } |
| 2965 | } |
| 2966 | } |
| 2967 | |
| 2968 | DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); |
| 2969 | } |
| 2970 | |
| 2971 | void SelectionDAGBuilder::visitFSub(const User &I) { |
| 2972 | // -0.0 - X --> fneg |
| 2973 | Type *Ty = I.getType(); |
| 2974 | if (isa<Constant>(I.getOperand(0)) && |
| 2975 | I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { |
| 2976 | SDValue Op2 = getValue(I.getOperand(1)); |
| 2977 | setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), |
| 2978 | Op2.getValueType(), Op2)); |
| 2979 | return; |
| 2980 | } |
| 2981 | |
| 2982 | visitBinary(I, ISD::FSUB); |
| 2983 | } |
| 2984 | |
| 2985 | /// Checks if the given instruction performs a vector reduction, in which case |
| 2986 | /// we have the freedom to alter the elements in the result as long as the |
| 2987 | /// reduction of them stays unchanged. |
| 2988 | static bool isVectorReductionOp(const User *I) { |
| 2989 | const Instruction *Inst = dyn_cast<Instruction>(I); |
| 2990 | if (!Inst || !Inst->getType()->isVectorTy()) |
| 2991 | return false; |
| 2992 | |
| 2993 | auto OpCode = Inst->getOpcode(); |
| 2994 | switch (OpCode) { |
| 2995 | case Instruction::Add: |
| 2996 | case Instruction::Mul: |
| 2997 | case Instruction::And: |
| 2998 | case Instruction::Or: |
| 2999 | case Instruction::Xor: |
| 3000 | break; |
| 3001 | case Instruction::FAdd: |
| 3002 | case Instruction::FMul: |
| 3003 | if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) |
| 3004 | if (FPOp->getFastMathFlags().isFast()) |
| 3005 | break; |
| 3006 | LLVM_FALLTHROUGH; |
| 3007 | default: |
| 3008 | return false; |
| 3009 | } |
| 3010 | |
| 3011 | unsigned ElemNum = Inst->getType()->getVectorNumElements(); |
| 3012 | // Ensure the reduction size is a power of 2. |
| 3013 | if (!isPowerOf2_32(ElemNum)) |
| 3014 | return false; |
| 3015 | |
| 3016 | unsigned ElemNumToReduce = ElemNum; |
| 3017 | |
| 3018 | // Do DFS search on the def-use chain from the given instruction. We only |
| 3019 | // allow four kinds of operations during the search until we reach the |
| 3020 | // instruction that extracts the first element from the vector: |
| 3021 | // |
| 3022 | // 1. The reduction operation of the same opcode as the given instruction. |
| 3023 | // |
| 3024 | // 2. PHI node. |
| 3025 | // |
| 3026 | // 3. ShuffleVector instruction together with a reduction operation that |
| 3027 | // does a partial reduction. |
| 3028 | // |
| 3029 | // 4. ExtractElement that extracts the first element from the vector, and we |
| 3030 | // stop searching the def-use chain here. |
| 3031 | // |
| 3032 | // 3 & 4 above perform a reduction on all elements of the vector. We push defs |
| 3033 | // from 1-3 to the stack to continue the DFS. The given instruction is not |
| 3034 | // a reduction operation if we meet any other instructions other than those |
| 3035 | // listed above. |
| 3036 | |
| 3037 | SmallVector<const User *, 16> UsersToVisit{Inst}; |
| 3038 | SmallPtrSet<const User *, 16> Visited; |
| 3039 | bool = false; |
| 3040 | |
| 3041 | while (!UsersToVisit.empty()) { |
| 3042 | auto User = UsersToVisit.back(); |
| 3043 | UsersToVisit.pop_back(); |
| 3044 | if (!Visited.insert(User).second) |
| 3045 | continue; |
| 3046 | |
| 3047 | for (const auto &U : User->users()) { |
| 3048 | auto Inst = dyn_cast<Instruction>(U); |
| 3049 | if (!Inst) |
| 3050 | return false; |
| 3051 | |
| 3052 | if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { |
| 3053 | if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) |
| 3054 | if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) |
| 3055 | return false; |
| 3056 | UsersToVisit.push_back(U); |
| 3057 | } else if (const ShuffleVectorInst *ShufInst = |
| 3058 | dyn_cast<ShuffleVectorInst>(U)) { |
| 3059 | // Detect the following pattern: A ShuffleVector instruction together |
| 3060 | // with a reduction that do partial reduction on the first and second |
| 3061 | // ElemNumToReduce / 2 elements, and store the result in |
| 3062 | // ElemNumToReduce / 2 elements in another vector. |
| 3063 | |
| 3064 | unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); |
| 3065 | if (ResultElements < ElemNum) |
| 3066 | return false; |
| 3067 | |
| 3068 | if (ElemNumToReduce == 1) |
| 3069 | return false; |
| 3070 | if (!isa<UndefValue>(U->getOperand(1))) |
| 3071 | return false; |
| 3072 | for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) |
| 3073 | if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) |
| 3074 | return false; |
| 3075 | for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) |
| 3076 | if (ShufInst->getMaskValue(i) != -1) |
| 3077 | return false; |
| 3078 | |
| 3079 | // There is only one user of this ShuffleVector instruction, which |
| 3080 | // must be a reduction operation. |
| 3081 | if (!U->hasOneUse()) |
| 3082 | return false; |
| 3083 | |
| 3084 | auto U2 = dyn_cast<Instruction>(*U->user_begin()); |
| 3085 | if (!U2 || U2->getOpcode() != OpCode) |
| 3086 | return false; |
| 3087 | |
| 3088 | // Check operands of the reduction operation. |
| 3089 | if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || |
| 3090 | (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { |
| 3091 | UsersToVisit.push_back(U2); |
| 3092 | ElemNumToReduce /= 2; |
| 3093 | } else |
| 3094 | return false; |
| 3095 | } else if (isa<ExtractElementInst>(U)) { |
| 3096 | // At this moment we should have reduced all elements in the vector. |
| 3097 | if (ElemNumToReduce != 1) |
| 3098 | return false; |
| 3099 | |
| 3100 | const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); |
| 3101 | if (!Val || !Val->isZero()) |
| 3102 | return false; |
| 3103 | |
| 3104 | ReduxExtracted = true; |
| 3105 | } else |
| 3106 | return false; |
| 3107 | } |
| 3108 | } |
| 3109 | return ReduxExtracted; |
| 3110 | } |
| 3111 | |
| 3112 | void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { |
| 3113 | SDNodeFlags Flags; |
| 3114 | |
| 3115 | SDValue Op = getValue(I.getOperand(0)); |
| 3116 | SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), |
| 3117 | Op, Flags); |
| 3118 | setValue(&I, UnNodeValue); |
| 3119 | } |
| 3120 | |
| 3121 | void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { |
| 3122 | SDNodeFlags Flags; |
| 3123 | if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { |
| 3124 | Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); |
| 3125 | Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); |
| 3126 | } |
| 3127 | if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { |
| 3128 | Flags.setExact(ExactOp->isExact()); |
| 3129 | } |
| 3130 | if (isVectorReductionOp(&I)) { |
| 3131 | Flags.setVectorReduction(true); |
| 3132 | LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n" ); |
| 3133 | } |
| 3134 | |
| 3135 | SDValue Op1 = getValue(I.getOperand(0)); |
| 3136 | SDValue Op2 = getValue(I.getOperand(1)); |
| 3137 | SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), |
| 3138 | Op1, Op2, Flags); |
| 3139 | setValue(&I, BinNodeValue); |
| 3140 | } |
| 3141 | |
| 3142 | void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { |
| 3143 | SDValue Op1 = getValue(I.getOperand(0)); |
| 3144 | SDValue Op2 = getValue(I.getOperand(1)); |
| 3145 | |
| 3146 | EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( |
| 3147 | Op1.getValueType(), DAG.getDataLayout()); |
| 3148 | |
| 3149 | // Coerce the shift amount to the right type if we can. |
| 3150 | if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { |
| 3151 | unsigned ShiftSize = ShiftTy.getSizeInBits(); |
| 3152 | unsigned Op2Size = Op2.getValueSizeInBits(); |
| 3153 | SDLoc DL = getCurSDLoc(); |
| 3154 | |
| 3155 | // If the operand is smaller than the shift count type, promote it. |
| 3156 | if (ShiftSize > Op2Size) |
| 3157 | Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); |
| 3158 | |
| 3159 | // If the operand is larger than the shift count type but the shift |
| 3160 | // count type has enough bits to represent any shift value, truncate |
| 3161 | // it now. This is a common case and it exposes the truncate to |
| 3162 | // optimization early. |
| 3163 | else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) |
| 3164 | Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); |
| 3165 | // Otherwise we'll need to temporarily settle for some other convenient |
| 3166 | // type. Type legalization will make adjustments once the shiftee is split. |
| 3167 | else |
| 3168 | Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); |
| 3169 | } |
| 3170 | |
| 3171 | bool nuw = false; |
| 3172 | bool nsw = false; |
| 3173 | bool exact = false; |
| 3174 | |
| 3175 | if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { |
| 3176 | |
| 3177 | if (const OverflowingBinaryOperator *OFBinOp = |
| 3178 | dyn_cast<const OverflowingBinaryOperator>(&I)) { |
| 3179 | nuw = OFBinOp->hasNoUnsignedWrap(); |
| 3180 | nsw = OFBinOp->hasNoSignedWrap(); |
| 3181 | } |
| 3182 | if (const PossiblyExactOperator *ExactOp = |
| 3183 | dyn_cast<const PossiblyExactOperator>(&I)) |
| 3184 | exact = ExactOp->isExact(); |
| 3185 | } |
| 3186 | SDNodeFlags Flags; |
| 3187 | Flags.setExact(exact); |
| 3188 | Flags.setNoSignedWrap(nsw); |
| 3189 | Flags.setNoUnsignedWrap(nuw); |
| 3190 | SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, |
| 3191 | Flags); |
| 3192 | setValue(&I, Res); |
| 3193 | } |
| 3194 | |
| 3195 | void SelectionDAGBuilder::visitSDiv(const User &I) { |
| 3196 | SDValue Op1 = getValue(I.getOperand(0)); |
| 3197 | SDValue Op2 = getValue(I.getOperand(1)); |
| 3198 | |
| 3199 | SDNodeFlags Flags; |
| 3200 | Flags.setExact(isa<PossiblyExactOperator>(&I) && |
| 3201 | cast<PossiblyExactOperator>(&I)->isExact()); |
| 3202 | setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, |
| 3203 | Op2, Flags)); |
| 3204 | } |
| 3205 | |
| 3206 | void SelectionDAGBuilder::visitICmp(const User &I) { |
| 3207 | ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; |
| 3208 | if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) |
| 3209 | predicate = IC->getPredicate(); |
| 3210 | else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) |
| 3211 | predicate = ICmpInst::Predicate(IC->getPredicate()); |
| 3212 | SDValue Op1 = getValue(I.getOperand(0)); |
| 3213 | SDValue Op2 = getValue(I.getOperand(1)); |
| 3214 | ISD::CondCode Opcode = getICmpCondCode(predicate); |
| 3215 | |
| 3216 | auto &TLI = DAG.getTargetLoweringInfo(); |
| 3217 | EVT MemVT = |
| 3218 | TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); |
| 3219 | |
| 3220 | // If a pointer's DAG type is larger than its memory type then the DAG values |
| 3221 | // are zero-extended. This breaks signed comparisons so truncate back to the |
| 3222 | // underlying type before doing the compare. |
| 3223 | if (Op1.getValueType() != MemVT) { |
| 3224 | Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); |
| 3225 | Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); |
| 3226 | } |
| 3227 | |
| 3228 | EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 3229 | I.getType()); |
| 3230 | setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); |
| 3231 | } |
| 3232 | |
| 3233 | void SelectionDAGBuilder::visitFCmp(const User &I) { |
| 3234 | FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; |
| 3235 | if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) |
| 3236 | predicate = FC->getPredicate(); |
| 3237 | else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) |
| 3238 | predicate = FCmpInst::Predicate(FC->getPredicate()); |
| 3239 | SDValue Op1 = getValue(I.getOperand(0)); |
| 3240 | SDValue Op2 = getValue(I.getOperand(1)); |
| 3241 | |
| 3242 | ISD::CondCode Condition = getFCmpCondCode(predicate); |
| 3243 | auto *FPMO = dyn_cast<FPMathOperator>(&I); |
| 3244 | if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) |
| 3245 | Condition = getFCmpCodeWithoutNaN(Condition); |
| 3246 | |
| 3247 | EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 3248 | I.getType()); |
| 3249 | setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); |
| 3250 | } |
| 3251 | |
| 3252 | // Check if the condition of the select has one use or two users that are both |
| 3253 | // selects with the same condition. |
| 3254 | static bool hasOnlySelectUsers(const Value *Cond) { |
| 3255 | return llvm::all_of(Cond->users(), [](const Value *V) { |
| 3256 | return isa<SelectInst>(V); |
| 3257 | }); |
| 3258 | } |
| 3259 | |
| 3260 | void SelectionDAGBuilder::visitSelect(const User &I) { |
| 3261 | SmallVector<EVT, 4> ValueVTs; |
| 3262 | ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), |
| 3263 | ValueVTs); |
| 3264 | unsigned NumValues = ValueVTs.size(); |
| 3265 | if (NumValues == 0) return; |
| 3266 | |
| 3267 | SmallVector<SDValue, 4> Values(NumValues); |
| 3268 | SDValue Cond = getValue(I.getOperand(0)); |
| 3269 | SDValue LHSVal = getValue(I.getOperand(1)); |
| 3270 | SDValue RHSVal = getValue(I.getOperand(2)); |
| 3271 | auto BaseOps = {Cond}; |
| 3272 | ISD::NodeType OpCode = Cond.getValueType().isVector() ? |
| 3273 | ISD::VSELECT : ISD::SELECT; |
| 3274 | |
| 3275 | bool IsUnaryAbs = false; |
| 3276 | |
| 3277 | // Min/max matching is only viable if all output VTs are the same. |
| 3278 | if (is_splat(ValueVTs)) { |
| 3279 | EVT VT = ValueVTs[0]; |
| 3280 | LLVMContext &Ctx = *DAG.getContext(); |
| 3281 | auto &TLI = DAG.getTargetLoweringInfo(); |
| 3282 | |
| 3283 | // We care about the legality of the operation after it has been type |
| 3284 | // legalized. |
| 3285 | while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && |
| 3286 | VT != TLI.getTypeToTransformTo(Ctx, VT)) |
| 3287 | VT = TLI.getTypeToTransformTo(Ctx, VT); |
| 3288 | |
| 3289 | // If the vselect is legal, assume we want to leave this as a vector setcc + |
| 3290 | // vselect. Otherwise, if this is going to be scalarized, we want to see if |
| 3291 | // min/max is legal on the scalar type. |
| 3292 | bool UseScalarMinMax = VT.isVector() && |
| 3293 | !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); |
| 3294 | |
| 3295 | Value *LHS, *RHS; |
| 3296 | auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); |
| 3297 | ISD::NodeType Opc = ISD::DELETED_NODE; |
| 3298 | switch (SPR.Flavor) { |
| 3299 | case SPF_UMAX: Opc = ISD::UMAX; break; |
| 3300 | case SPF_UMIN: Opc = ISD::UMIN; break; |
| 3301 | case SPF_SMAX: Opc = ISD::SMAX; break; |
| 3302 | case SPF_SMIN: Opc = ISD::SMIN; break; |
| 3303 | case SPF_FMINNUM: |
| 3304 | switch (SPR.NaNBehavior) { |
| 3305 | case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?" ); |
| 3306 | case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; |
| 3307 | case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; |
| 3308 | case SPNB_RETURNS_ANY: { |
| 3309 | if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) |
| 3310 | Opc = ISD::FMINNUM; |
| 3311 | else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) |
| 3312 | Opc = ISD::FMINIMUM; |
| 3313 | else if (UseScalarMinMax) |
| 3314 | Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? |
| 3315 | ISD::FMINNUM : ISD::FMINIMUM; |
| 3316 | break; |
| 3317 | } |
| 3318 | } |
| 3319 | break; |
| 3320 | case SPF_FMAXNUM: |
| 3321 | switch (SPR.NaNBehavior) { |
| 3322 | case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?" ); |
| 3323 | case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; |
| 3324 | case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; |
| 3325 | case SPNB_RETURNS_ANY: |
| 3326 | |
| 3327 | if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) |
| 3328 | Opc = ISD::FMAXNUM; |
| 3329 | else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) |
| 3330 | Opc = ISD::FMAXIMUM; |
| 3331 | else if (UseScalarMinMax) |
| 3332 | Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? |
| 3333 | ISD::FMAXNUM : ISD::FMAXIMUM; |
| 3334 | break; |
| 3335 | } |
| 3336 | break; |
| 3337 | case SPF_ABS: |
| 3338 | IsUnaryAbs = true; |
| 3339 | Opc = ISD::ABS; |
| 3340 | break; |
| 3341 | case SPF_NABS: |
| 3342 | // TODO: we need to produce sub(0, abs(X)). |
| 3343 | default: break; |
| 3344 | } |
| 3345 | |
| 3346 | if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && |
| 3347 | (TLI.isOperationLegalOrCustom(Opc, VT) || |
| 3348 | (UseScalarMinMax && |
| 3349 | TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && |
| 3350 | // If the underlying comparison instruction is used by any other |
| 3351 | // instruction, the consumed instructions won't be destroyed, so it is |
| 3352 | // not profitable to convert to a min/max. |
| 3353 | hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { |
| 3354 | OpCode = Opc; |
| 3355 | LHSVal = getValue(LHS); |
| 3356 | RHSVal = getValue(RHS); |
| 3357 | BaseOps = {}; |
| 3358 | } |
| 3359 | |
| 3360 | if (IsUnaryAbs) { |
| 3361 | OpCode = Opc; |
| 3362 | LHSVal = getValue(LHS); |
| 3363 | BaseOps = {}; |
| 3364 | } |
| 3365 | } |
| 3366 | |
| 3367 | if (IsUnaryAbs) { |
| 3368 | for (unsigned i = 0; i != NumValues; ++i) { |
| 3369 | Values[i] = |
| 3370 | DAG.getNode(OpCode, getCurSDLoc(), |
| 3371 | LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), |
| 3372 | SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); |
| 3373 | } |
| 3374 | } else { |
| 3375 | for (unsigned i = 0; i != NumValues; ++i) { |
| 3376 | SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); |
| 3377 | Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); |
| 3378 | Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); |
| 3379 | Values[i] = DAG.getNode( |
| 3380 | OpCode, getCurSDLoc(), |
| 3381 | LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); |
| 3382 | } |
| 3383 | } |
| 3384 | |
| 3385 | setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), |
| 3386 | DAG.getVTList(ValueVTs), Values)); |
| 3387 | } |
| 3388 | |
| 3389 | void SelectionDAGBuilder::visitTrunc(const User &I) { |
| 3390 | // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). |
| 3391 | SDValue N = getValue(I.getOperand(0)); |
| 3392 | EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 3393 | I.getType()); |
| 3394 | setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); |
| 3395 | } |
| 3396 | |
| 3397 | void SelectionDAGBuilder::visitZExt(const User &I) { |
| 3398 | // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). |
| 3399 | // ZExt also can't be a cast to bool for same reason. So, nothing much to do |
| 3400 | SDValue N = getValue(I.getOperand(0)); |
| 3401 | EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 3402 | I.getType()); |
| 3403 | setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); |
| 3404 | } |
| 3405 | |
| 3406 | void SelectionDAGBuilder::visitSExt(const User &I) { |
| 3407 | // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). |
| 3408 | // SExt also can't be a cast to bool for same reason. So, nothing much to do |
| 3409 | SDValue N = getValue(I.getOperand(0)); |
| 3410 | EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 3411 | I.getType()); |
| 3412 | setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); |
| 3413 | } |
| 3414 | |
| 3415 | void SelectionDAGBuilder::visitFPTrunc(const User &I) { |
| 3416 | // FPTrunc is never a no-op cast, no need to check |
| 3417 | SDValue N = getValue(I.getOperand(0)); |
| 3418 | SDLoc dl = getCurSDLoc(); |
| 3419 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 3420 | EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 3421 | setValue(&I, |
| 3422 | DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, |
| 3423 | DAG.getTargetConstant( |
| 3424 | 0, dl, TLI.getPointerRangeTy(DAG.getDataLayout())))); |
| 3425 | } |
| 3426 | |
| 3427 | void SelectionDAGBuilder::visitFPExt(const User &I) { |
| 3428 | // FPExt is never a no-op cast, no need to check |
| 3429 | SDValue N = getValue(I.getOperand(0)); |
| 3430 | EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 3431 | I.getType()); |
| 3432 | setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); |
| 3433 | } |
| 3434 | |
| 3435 | void SelectionDAGBuilder::visitFPToUI(const User &I) { |
| 3436 | // FPToUI is never a no-op cast, no need to check |
| 3437 | SDValue N = getValue(I.getOperand(0)); |
| 3438 | EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 3439 | I.getType()); |
| 3440 | setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); |
| 3441 | } |
| 3442 | |
| 3443 | void SelectionDAGBuilder::visitFPToSI(const User &I) { |
| 3444 | // FPToSI is never a no-op cast, no need to check |
| 3445 | SDValue N = getValue(I.getOperand(0)); |
| 3446 | EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 3447 | I.getType()); |
| 3448 | setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); |
| 3449 | } |
| 3450 | |
| 3451 | void SelectionDAGBuilder::visitUIToFP(const User &I) { |
| 3452 | // UIToFP is never a no-op cast, no need to check |
| 3453 | SDValue N = getValue(I.getOperand(0)); |
| 3454 | EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 3455 | I.getType()); |
| 3456 | setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); |
| 3457 | } |
| 3458 | |
| 3459 | void SelectionDAGBuilder::visitSIToFP(const User &I) { |
| 3460 | // SIToFP is never a no-op cast, no need to check |
| 3461 | SDValue N = getValue(I.getOperand(0)); |
| 3462 | EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 3463 | I.getType()); |
| 3464 | setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); |
| 3465 | } |
| 3466 | |
| 3467 | void SelectionDAGBuilder::visitPtrToInt(const User &I) { |
| 3468 | // What to do depends on the size of the integer and the size of the pointer. |
| 3469 | // We can either truncate, zero extend, or no-op, accordingly. |
| 3470 | SDValue N = getValue(I.getOperand(0)); |
| 3471 | auto &TLI = DAG.getTargetLoweringInfo(); |
| 3472 | EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 3473 | I.getType()); |
| 3474 | if (N.getValueType().isFatPointer()) { |
| 3475 | setValue(&I, DAG.getNode(ISD::PTRTOINT, getCurSDLoc(), DestVT, N)); |
| 3476 | return; |
| 3477 | } |
| 3478 | EVT PtrMemVT = |
| 3479 | TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); |
| 3480 | N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); |
| 3481 | N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); |
| 3482 | setValue(&I, N); |
| 3483 | } |
| 3484 | |
| 3485 | void SelectionDAGBuilder::visitIntToPtr(const User &I) { |
| 3486 | // What to do depends on the size of the integer and the size of the pointer. |
| 3487 | // We can either truncate, zero extend, or no-op, accordingly. |
| 3488 | SDValue N = getValue(I.getOperand(0)); |
| 3489 | auto &TLI = DAG.getTargetLoweringInfo(); |
| 3490 | EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 3491 | if (DestVT.isFatPointer()) { |
| 3492 | setValue(&I, DAG.getNode(ISD::INTTOPTR, getCurSDLoc(), DestVT, N)); |
| 3493 | return; |
| 3494 | } |
| 3495 | EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); |
| 3496 | N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); |
| 3497 | N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); |
| 3498 | setValue(&I, N); |
| 3499 | } |
| 3500 | |
| 3501 | void SelectionDAGBuilder::visitBitCast(const User &I) { |
| 3502 | SDValue N = getValue(I.getOperand(0)); |
| 3503 | SDLoc dl = getCurSDLoc(); |
| 3504 | EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 3505 | I.getType()); |
| 3506 | |
| 3507 | // BitCast assures us that source and destination are the same size so this is |
| 3508 | // either a BITCAST or a no-op. |
| 3509 | if (DestVT != N.getValueType()) |
| 3510 | setValue(&I, DAG.getNode(ISD::BITCAST, dl, |
| 3511 | DestVT, N)); // convert types. |
| 3512 | // Check if the original LLVM IR Operand was a ConstantInt, because getValue() |
| 3513 | // might fold any kind of constant expression to an integer constant and that |
| 3514 | // is not what we are looking for. Only recognize a bitcast of a genuine |
| 3515 | // constant integer as an opaque constant. |
| 3516 | else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) |
| 3517 | setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, |
| 3518 | /*isOpaque*/true)); |
| 3519 | else |
| 3520 | setValue(&I, N); // noop cast. |
| 3521 | } |
| 3522 | |
| 3523 | void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { |
| 3524 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 3525 | const Value *SV = I.getOperand(0); |
| 3526 | SDValue N = getValue(SV); |
| 3527 | EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 3528 | |
| 3529 | unsigned SrcAS = SV->getType()->getPointerAddressSpace(); |
| 3530 | unsigned DestAS = I.getType()->getPointerAddressSpace(); |
| 3531 | |
| 3532 | if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) |
| 3533 | N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); |
| 3534 | |
| 3535 | setValue(&I, N); |
| 3536 | } |
| 3537 | |
| 3538 | void SelectionDAGBuilder::visitInsertElement(const User &I) { |
| 3539 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 3540 | SDValue InVec = getValue(I.getOperand(0)); |
| 3541 | SDValue InVal = getValue(I.getOperand(1)); |
| 3542 | SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), |
| 3543 | TLI.getVectorIdxTy(DAG.getDataLayout())); |
| 3544 | setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), |
| 3545 | TLI.getValueType(DAG.getDataLayout(), I.getType()), |
| 3546 | InVec, InVal, InIdx)); |
| 3547 | } |
| 3548 | |
| 3549 | void SelectionDAGBuilder::(const User &I) { |
| 3550 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 3551 | SDValue InVec = getValue(I.getOperand(0)); |
| 3552 | SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), |
| 3553 | TLI.getVectorIdxTy(DAG.getDataLayout())); |
| 3554 | setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), |
| 3555 | TLI.getValueType(DAG.getDataLayout(), I.getType()), |
| 3556 | InVec, InIdx)); |
| 3557 | } |
| 3558 | |
| 3559 | void SelectionDAGBuilder::visitShuffleVector(const User &I) { |
| 3560 | SDValue Src1 = getValue(I.getOperand(0)); |
| 3561 | SDValue Src2 = getValue(I.getOperand(1)); |
| 3562 | SDLoc DL = getCurSDLoc(); |
| 3563 | |
| 3564 | SmallVector<int, 8> Mask; |
| 3565 | ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); |
| 3566 | unsigned MaskNumElts = Mask.size(); |
| 3567 | |
| 3568 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 3569 | EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 3570 | EVT SrcVT = Src1.getValueType(); |
| 3571 | unsigned SrcNumElts = SrcVT.getVectorNumElements(); |
| 3572 | |
| 3573 | if (SrcNumElts == MaskNumElts) { |
| 3574 | setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); |
| 3575 | return; |
| 3576 | } |
| 3577 | |
| 3578 | // Normalize the shuffle vector since mask and vector length don't match. |
| 3579 | if (SrcNumElts < MaskNumElts) { |
| 3580 | // Mask is longer than the source vectors. We can use concatenate vector to |
| 3581 | // make the mask and vectors lengths match. |
| 3582 | |
| 3583 | if (MaskNumElts % SrcNumElts == 0) { |
| 3584 | // Mask length is a multiple of the source vector length. |
| 3585 | // Check if the shuffle is some kind of concatenation of the input |
| 3586 | // vectors. |
| 3587 | unsigned NumConcat = MaskNumElts / SrcNumElts; |
| 3588 | bool IsConcat = true; |
| 3589 | SmallVector<int, 8> ConcatSrcs(NumConcat, -1); |
| 3590 | for (unsigned i = 0; i != MaskNumElts; ++i) { |
| 3591 | int Idx = Mask[i]; |
| 3592 | if (Idx < 0) |
| 3593 | continue; |
| 3594 | // Ensure the indices in each SrcVT sized piece are sequential and that |
| 3595 | // the same source is used for the whole piece. |
| 3596 | if ((Idx % SrcNumElts != (i % SrcNumElts)) || |
| 3597 | (ConcatSrcs[i / SrcNumElts] >= 0 && |
| 3598 | ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { |
| 3599 | IsConcat = false; |
| 3600 | break; |
| 3601 | } |
| 3602 | // Remember which source this index came from. |
| 3603 | ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; |
| 3604 | } |
| 3605 | |
| 3606 | // The shuffle is concatenating multiple vectors together. Just emit |
| 3607 | // a CONCAT_VECTORS operation. |
| 3608 | if (IsConcat) { |
| 3609 | SmallVector<SDValue, 8> ConcatOps; |
| 3610 | for (auto Src : ConcatSrcs) { |
| 3611 | if (Src < 0) |
| 3612 | ConcatOps.push_back(DAG.getUNDEF(SrcVT)); |
| 3613 | else if (Src == 0) |
| 3614 | ConcatOps.push_back(Src1); |
| 3615 | else |
| 3616 | ConcatOps.push_back(Src2); |
| 3617 | } |
| 3618 | setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); |
| 3619 | return; |
| 3620 | } |
| 3621 | } |
| 3622 | |
| 3623 | unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); |
| 3624 | unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; |
| 3625 | EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), |
| 3626 | PaddedMaskNumElts); |
| 3627 | |
| 3628 | // Pad both vectors with undefs to make them the same length as the mask. |
| 3629 | SDValue UndefVal = DAG.getUNDEF(SrcVT); |
| 3630 | |
| 3631 | SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); |
| 3632 | SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); |
| 3633 | MOps1[0] = Src1; |
| 3634 | MOps2[0] = Src2; |
| 3635 | |
| 3636 | Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); |
| 3637 | Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); |
| 3638 | |
| 3639 | // Readjust mask for new input vector length. |
| 3640 | SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); |
| 3641 | for (unsigned i = 0; i != MaskNumElts; ++i) { |
| 3642 | int Idx = Mask[i]; |
| 3643 | if (Idx >= (int)SrcNumElts) |
| 3644 | Idx -= SrcNumElts - PaddedMaskNumElts; |
| 3645 | MappedOps[i] = Idx; |
| 3646 | } |
| 3647 | |
| 3648 | SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); |
| 3649 | |
| 3650 | // If the concatenated vector was padded, extract a subvector with the |
| 3651 | // correct number of elements. |
| 3652 | if (MaskNumElts != PaddedMaskNumElts) |
| 3653 | Result = DAG.getNode( |
| 3654 | ISD::EXTRACT_SUBVECTOR, DL, VT, Result, |
| 3655 | DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); |
| 3656 | |
| 3657 | setValue(&I, Result); |
| 3658 | return; |
| 3659 | } |
| 3660 | |
| 3661 | if (SrcNumElts > MaskNumElts) { |
| 3662 | // Analyze the access pattern of the vector to see if we can extract |
| 3663 | // two subvectors and do the shuffle. |
| 3664 | int StartIdx[2] = { -1, -1 }; // StartIdx to extract from |
| 3665 | bool = true; |
| 3666 | for (int Idx : Mask) { |
| 3667 | unsigned Input = 0; |
| 3668 | if (Idx < 0) |
| 3669 | continue; |
| 3670 | |
| 3671 | if (Idx >= (int)SrcNumElts) { |
| 3672 | Input = 1; |
| 3673 | Idx -= SrcNumElts; |
| 3674 | } |
| 3675 | |
| 3676 | // If all the indices come from the same MaskNumElts sized portion of |
| 3677 | // the sources we can use extract. Also make sure the extract wouldn't |
| 3678 | // extract past the end of the source. |
| 3679 | int NewStartIdx = alignDown(Idx, MaskNumElts); |
| 3680 | if (NewStartIdx + MaskNumElts > SrcNumElts || |
| 3681 | (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) |
| 3682 | CanExtract = false; |
| 3683 | // Make sure we always update StartIdx as we use it to track if all |
| 3684 | // elements are undef. |
| 3685 | StartIdx[Input] = NewStartIdx; |
| 3686 | } |
| 3687 | |
| 3688 | if (StartIdx[0] < 0 && StartIdx[1] < 0) { |
| 3689 | setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. |
| 3690 | return; |
| 3691 | } |
| 3692 | if (CanExtract) { |
| 3693 | // Extract appropriate subvector and generate a vector shuffle |
| 3694 | for (unsigned Input = 0; Input < 2; ++Input) { |
| 3695 | SDValue &Src = Input == 0 ? Src1 : Src2; |
| 3696 | if (StartIdx[Input] < 0) |
| 3697 | Src = DAG.getUNDEF(VT); |
| 3698 | else { |
| 3699 | Src = DAG.getNode( |
| 3700 | ISD::EXTRACT_SUBVECTOR, DL, VT, Src, |
| 3701 | DAG.getConstant(StartIdx[Input], DL, |
| 3702 | TLI.getVectorIdxTy(DAG.getDataLayout()))); |
| 3703 | } |
| 3704 | } |
| 3705 | |
| 3706 | // Calculate new mask. |
| 3707 | SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); |
| 3708 | for (int &Idx : MappedOps) { |
| 3709 | if (Idx >= (int)SrcNumElts) |
| 3710 | Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; |
| 3711 | else if (Idx >= 0) |
| 3712 | Idx -= StartIdx[0]; |
| 3713 | } |
| 3714 | |
| 3715 | setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); |
| 3716 | return; |
| 3717 | } |
| 3718 | } |
| 3719 | |
| 3720 | // We can't use either concat vectors or extract subvectors so fall back to |
| 3721 | // replacing the shuffle with extract and build vector. |
| 3722 | // to insert and build vector. |
| 3723 | EVT EltVT = VT.getVectorElementType(); |
| 3724 | EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); |
| 3725 | SmallVector<SDValue,8> Ops; |
| 3726 | for (int Idx : Mask) { |
| 3727 | SDValue Res; |
| 3728 | |
| 3729 | if (Idx < 0) { |
| 3730 | Res = DAG.getUNDEF(EltVT); |
| 3731 | } else { |
| 3732 | SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; |
| 3733 | if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; |
| 3734 | |
| 3735 | Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, |
| 3736 | EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); |
| 3737 | } |
| 3738 | |
| 3739 | Ops.push_back(Res); |
| 3740 | } |
| 3741 | |
| 3742 | setValue(&I, DAG.getBuildVector(VT, DL, Ops)); |
| 3743 | } |
| 3744 | |
| 3745 | void SelectionDAGBuilder::visitInsertValue(const User &I) { |
| 3746 | ArrayRef<unsigned> Indices; |
| 3747 | if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) |
| 3748 | Indices = IV->getIndices(); |
| 3749 | else |
| 3750 | Indices = cast<ConstantExpr>(&I)->getIndices(); |
| 3751 | |
| 3752 | const Value *Op0 = I.getOperand(0); |
| 3753 | const Value *Op1 = I.getOperand(1); |
| 3754 | Type *AggTy = I.getType(); |
| 3755 | Type *ValTy = Op1->getType(); |
| 3756 | bool IntoUndef = isa<UndefValue>(Op0); |
| 3757 | bool FromUndef = isa<UndefValue>(Op1); |
| 3758 | |
| 3759 | unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); |
| 3760 | |
| 3761 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 3762 | SmallVector<EVT, 4> AggValueVTs; |
| 3763 | ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); |
| 3764 | SmallVector<EVT, 4> ValValueVTs; |
| 3765 | ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); |
| 3766 | |
| 3767 | unsigned NumAggValues = AggValueVTs.size(); |
| 3768 | unsigned NumValValues = ValValueVTs.size(); |
| 3769 | SmallVector<SDValue, 4> Values(NumAggValues); |
| 3770 | |
| 3771 | // Ignore an insertvalue that produces an empty object |
| 3772 | if (!NumAggValues) { |
| 3773 | setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); |
| 3774 | return; |
| 3775 | } |
| 3776 | |
| 3777 | SDValue Agg = getValue(Op0); |
| 3778 | unsigned i = 0; |
| 3779 | // Copy the beginning value(s) from the original aggregate. |
| 3780 | for (; i != LinearIndex; ++i) |
| 3781 | Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : |
| 3782 | SDValue(Agg.getNode(), Agg.getResNo() + i); |
| 3783 | // Copy values from the inserted value(s). |
| 3784 | if (NumValValues) { |
| 3785 | SDValue Val = getValue(Op1); |
| 3786 | for (; i != LinearIndex + NumValValues; ++i) |
| 3787 | Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : |
| 3788 | SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); |
| 3789 | } |
| 3790 | // Copy remaining value(s) from the original aggregate. |
| 3791 | for (; i != NumAggValues; ++i) |
| 3792 | Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : |
| 3793 | SDValue(Agg.getNode(), Agg.getResNo() + i); |
| 3794 | |
| 3795 | setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), |
| 3796 | DAG.getVTList(AggValueVTs), Values)); |
| 3797 | } |
| 3798 | |
| 3799 | void SelectionDAGBuilder::(const User &I) { |
| 3800 | ArrayRef<unsigned> Indices; |
| 3801 | if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) |
| 3802 | Indices = EV->getIndices(); |
| 3803 | else |
| 3804 | Indices = cast<ConstantExpr>(&I)->getIndices(); |
| 3805 | |
| 3806 | const Value *Op0 = I.getOperand(0); |
| 3807 | Type *AggTy = Op0->getType(); |
| 3808 | Type *ValTy = I.getType(); |
| 3809 | bool OutOfUndef = isa<UndefValue>(Op0); |
| 3810 | |
| 3811 | unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); |
| 3812 | |
| 3813 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 3814 | SmallVector<EVT, 4> ValValueVTs; |
| 3815 | ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); |
| 3816 | |
| 3817 | unsigned NumValValues = ValValueVTs.size(); |
| 3818 | |
| 3819 | // Ignore a extractvalue that produces an empty object |
| 3820 | if (!NumValValues) { |
| 3821 | setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); |
| 3822 | return; |
| 3823 | } |
| 3824 | |
| 3825 | SmallVector<SDValue, 4> Values(NumValValues); |
| 3826 | |
| 3827 | SDValue Agg = getValue(Op0); |
| 3828 | // Copy out the selected value(s). |
| 3829 | for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) |
| 3830 | Values[i - LinearIndex] = |
| 3831 | OutOfUndef ? |
| 3832 | DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : |
| 3833 | SDValue(Agg.getNode(), Agg.getResNo() + i); |
| 3834 | |
| 3835 | setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), |
| 3836 | DAG.getVTList(ValValueVTs), Values)); |
| 3837 | } |
| 3838 | |
| 3839 | void SelectionDAGBuilder::visitGetElementPtr(const User &I) { |
| 3840 | Value *Op0 = I.getOperand(0); |
| 3841 | // Note that the pointer operand may be a vector of pointers. Take the scalar |
| 3842 | // element which holds a pointer. |
| 3843 | unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); |
| 3844 | SDValue N = getValue(Op0); |
| 3845 | SDLoc dl = getCurSDLoc(); |
| 3846 | auto &TLI = DAG.getTargetLoweringInfo(); |
| 3847 | MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); |
| 3848 | MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); |
| 3849 | |
| 3850 | // FIXME: This does not work on GEPs with vectors and fat pointers, but CHERI |
| 3851 | // currently doesn't have a vector unit so that is probably not a problem. |
| 3852 | bool FatPointer = N.getValueType().isFatPointer(); |
| 3853 | SDValue OrigN = N; |
| 3854 | |
| 3855 | if (FatPointer) { |
| 3856 | N = DAG.getIntPtrConstant(0, dl); |
| 3857 | } |
| 3858 | |
| 3859 | // Normalize Vector GEP - all scalar operands should be converted to the |
| 3860 | // splat vector. |
| 3861 | unsigned VectorWidth = I.getType()->isVectorTy() ? |
| 3862 | cast<VectorType>(I.getType())->getVectorNumElements() : 0; |
| 3863 | |
| 3864 | if (VectorWidth && !N.getValueType().isVector()) { |
| 3865 | LLVMContext &Context = *DAG.getContext(); |
| 3866 | EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); |
| 3867 | N = DAG.getSplatBuildVector(VT, dl, N); |
| 3868 | } |
| 3869 | |
| 3870 | for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); |
| 3871 | GTI != E; ++GTI) { |
| 3872 | const Value *Idx = GTI.getOperand(); |
| 3873 | if (StructType *StTy = GTI.getStructTypeOrNull()) { |
| 3874 | unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); |
| 3875 | if (Field) { |
| 3876 | // N = N + Offset |
| 3877 | uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); |
| 3878 | |
| 3879 | // In an inbounds GEP with an offset that is nonnegative even when |
| 3880 | // interpreted as signed, assume there is no unsigned overflow. |
| 3881 | SDNodeFlags Flags; |
| 3882 | if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) |
| 3883 | Flags.setNoUnsignedWrap(true); |
| 3884 | |
| 3885 | N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, |
| 3886 | DAG.getConstant(Offset, dl, N.getValueType()), Flags); |
| 3887 | } |
| 3888 | } else { |
| 3889 | unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); |
| 3890 | MVT IdxTy = MVT::getIntegerVT(IdxSize); |
| 3891 | APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); |
| 3892 | |
| 3893 | // If this is a scalar constant or a splat vector of constants, |
| 3894 | // handle it quickly. |
| 3895 | const auto *CI = dyn_cast<ConstantInt>(Idx); |
| 3896 | if (!CI && isa<ConstantDataVector>(Idx) && |
| 3897 | cast<ConstantDataVector>(Idx)->getSplatValue()) |
| 3898 | CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); |
| 3899 | |
| 3900 | if (CI) { |
| 3901 | if (CI->isZero()) |
| 3902 | continue; |
| 3903 | APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); |
| 3904 | LLVMContext &Context = *DAG.getContext(); |
| 3905 | SDValue OffsVal = VectorWidth ? |
| 3906 | DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : |
| 3907 | DAG.getConstant(Offs, dl, IdxTy); |
| 3908 | |
| 3909 | // In an inbouds GEP with an offset that is nonnegative even when |
| 3910 | // interpreted as signed, assume there is no unsigned overflow. |
| 3911 | SDNodeFlags Flags; |
| 3912 | if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) |
| 3913 | Flags.setNoUnsignedWrap(true); |
| 3914 | |
| 3915 | OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); |
| 3916 | |
| 3917 | N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); |
| 3918 | continue; |
| 3919 | } |
| 3920 | |
| 3921 | // N = N + Idx * ElementSize; |
| 3922 | SDValue IdxN = getValue(Idx); |
| 3923 | |
| 3924 | if (!IdxN.getValueType().isVector() && VectorWidth) { |
| 3925 | EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); |
| 3926 | IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); |
| 3927 | } |
| 3928 | |
| 3929 | // If the index is smaller or larger than intptr_t, truncate or extend |
| 3930 | // it. |
| 3931 | IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); |
| 3932 | |
| 3933 | // If this is a multiply by a power of two, turn it into a shl |
| 3934 | // immediately. This is a very common case. |
| 3935 | if (ElementSize != 1) { |
| 3936 | if (ElementSize.isPowerOf2()) { |
| 3937 | unsigned Amt = ElementSize.logBase2(); |
| 3938 | IdxN = DAG.getNode(ISD::SHL, dl, |
| 3939 | N.getValueType(), IdxN, |
| 3940 | DAG.getConstant(Amt, dl, IdxN.getValueType())); |
| 3941 | } else { |
| 3942 | SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl, |
| 3943 | IdxN.getValueType()); |
| 3944 | IdxN = DAG.getNode(ISD::MUL, dl, |
| 3945 | N.getValueType(), IdxN, Scale); |
| 3946 | } |
| 3947 | } |
| 3948 | |
| 3949 | N = DAG.getNode(ISD::ADD, dl, |
| 3950 | N.getValueType(), N, IdxN); |
| 3951 | } |
| 3952 | } |
| 3953 | |
| 3954 | if (FatPointer) |
| 3955 | N = DAG.getNode(ISD::PTRADD, getCurSDLoc(), OrigN.getValueType(), OrigN, |
| 3956 | N); |
| 3957 | |
| 3958 | if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) |
| 3959 | N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); |
| 3960 | |
| 3961 | setValue(&I, N); |
| 3962 | } |
| 3963 | |
| 3964 | void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { |
| 3965 | // If this is a fixed sized alloca in the entry block of the function, |
| 3966 | // allocate it statically on the stack. |
| 3967 | if (FuncInfo.StaticAllocaMap.count(&I)) |
| 3968 | return; // getValue will auto-populate this. |
| 3969 | |
| 3970 | SDLoc dl = getCurSDLoc(); |
| 3971 | Type *Ty = I.getAllocatedType(); |
| 3972 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 3973 | auto &DL = DAG.getDataLayout(); |
| 3974 | uint64_t TySize = DL.getTypeAllocSize(Ty); |
| 3975 | unsigned Align = |
| 3976 | std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); |
| 3977 | |
| 3978 | SDValue AllocSize = getValue(I.getArraySize()); |
| 3979 | |
| 3980 | EVT IntPtr = TLI.getPointerRangeTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); |
| 3981 | EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); |
| 3982 | if (AllocSize.getValueType() != IntPtr) |
| 3983 | AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); |
| 3984 | |
| 3985 | AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, |
| 3986 | AllocSize, |
| 3987 | DAG.getConstant(TySize, dl, IntPtr)); |
| 3988 | |
| 3989 | // Handle alignment. If the requested alignment is less than or equal to |
| 3990 | // the stack alignment, ignore it. If the size is greater than or equal to |
| 3991 | // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. |
| 3992 | unsigned StackAlign = |
| 3993 | DAG.getSubtarget().getFrameLowering()->getStackAlignment(); |
| 3994 | if (Align <= StackAlign) |
| 3995 | Align = 0; |
| 3996 | |
| 3997 | // Round the size of the allocation up to the stack alignment size |
| 3998 | // by add SA-1 to the size. This doesn't overflow because we're computing |
| 3999 | // an address inside an alloca. |
| 4000 | SDNodeFlags Flags; |
| 4001 | Flags.setNoUnsignedWrap(true); |
| 4002 | AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, |
| 4003 | DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); |
| 4004 | |
| 4005 | // Mask out the low bits for alignment purposes. |
| 4006 | AllocSize = |
| 4007 | DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, |
| 4008 | DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); |
| 4009 | |
| 4010 | SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; |
| 4011 | SDVTList VTs = DAG.getVTList(PtrTy, MVT::Other); |
| 4012 | SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); |
| 4013 | setValue(&I, DSA); |
| 4014 | DAG.setRoot(DSA.getValue(1)); |
| 4015 | |
| 4016 | assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); |
| 4017 | } |
| 4018 | |
| 4019 | void SelectionDAGBuilder::visitLoad(const LoadInst &I) { |
| 4020 | if (I.isAtomic()) |
| 4021 | return visitAtomicLoad(I); |
| 4022 | |
| 4023 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 4024 | const Value *SV = I.getOperand(0); |
| 4025 | if (TLI.supportSwiftError()) { |
| 4026 | // Swifterror values can come from either a function parameter with |
| 4027 | // swifterror attribute or an alloca with swifterror attribute. |
| 4028 | if (const Argument *Arg = dyn_cast<Argument>(SV)) { |
| 4029 | if (Arg->hasSwiftErrorAttr()) |
| 4030 | return visitLoadFromSwiftError(I); |
| 4031 | } |
| 4032 | |
| 4033 | if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { |
| 4034 | if (Alloca->isSwiftError()) |
| 4035 | return visitLoadFromSwiftError(I); |
| 4036 | } |
| 4037 | } |
| 4038 | |
| 4039 | SDValue Ptr = getValue(SV); |
| 4040 | |
| 4041 | Type *Ty = I.getType(); |
| 4042 | |
| 4043 | bool isVolatile = I.isVolatile(); |
| 4044 | bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; |
| 4045 | bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; |
| 4046 | bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); |
| 4047 | unsigned Alignment = I.getAlignment(); |
| 4048 | |
| 4049 | AAMDNodes AAInfo; |
| 4050 | I.getAAMetadata(AAInfo); |
| 4051 | const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); |
| 4052 | |
| 4053 | SmallVector<EVT, 4> ValueVTs, MemVTs; |
| 4054 | SmallVector<uint64_t, 4> Offsets; |
| 4055 | ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); |
| 4056 | unsigned NumValues = ValueVTs.size(); |
| 4057 | if (NumValues == 0) |
| 4058 | return; |
| 4059 | |
| 4060 | SDValue Root; |
| 4061 | bool ConstantMemory = false; |
| 4062 | if (isVolatile || NumValues > MaxParallelChains) |
| 4063 | // Serialize volatile loads with other side effects. |
| 4064 | Root = getRoot(); |
| 4065 | else if (AA && |
| 4066 | AA->pointsToConstantMemory(MemoryLocation( |
| 4067 | SV, |
| 4068 | LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), |
| 4069 | AAInfo))) { |
| 4070 | // Do not serialize (non-volatile) loads of constant memory with anything. |
| 4071 | Root = DAG.getEntryNode(); |
| 4072 | ConstantMemory = true; |
| 4073 | } else { |
| 4074 | // Do not serialize non-volatile loads against each other. |
| 4075 | Root = DAG.getRoot(); |
| 4076 | } |
| 4077 | |
| 4078 | SDLoc dl = getCurSDLoc(); |
| 4079 | |
| 4080 | if (isVolatile) |
| 4081 | Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); |
| 4082 | |
| 4083 | // An aggregate load cannot wrap around the address space, so offsets to its |
| 4084 | // parts don't wrap either. |
| 4085 | SDNodeFlags Flags; |
| 4086 | Flags.setNoUnsignedWrap(true); |
| 4087 | |
| 4088 | SmallVector<SDValue, 4> Values(NumValues); |
| 4089 | SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); |
| 4090 | unsigned ChainI = 0; |
| 4091 | for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { |
| 4092 | // Serializing loads here may result in excessive register pressure, and |
| 4093 | // TokenFactor places arbitrary choke points on the scheduler. SD scheduling |
| 4094 | // could recover a bit by hoisting nodes upward in the chain by recognizing |
| 4095 | // they are side-effect free or do not alias. The optimizer should really |
| 4096 | // avoid this case by converting large object/array copies to llvm.memcpy |
| 4097 | // (MaxParallelChains should always remain as failsafe). |
| 4098 | if (ChainI == MaxParallelChains) { |
| 4099 | assert(PendingLoads.empty() && "PendingLoads must be serialized first" ); |
| 4100 | SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, |
| 4101 | makeArrayRef(Chains.data(), ChainI)); |
| 4102 | Root = Chain; |
| 4103 | ChainI = 0; |
| 4104 | } |
| 4105 | SDValue A = Offsets[i] ? DAG.getPointerAdd(dl, Ptr, Offsets[i], Flags) : Ptr; |
| 4106 | auto MMOFlags = MachineMemOperand::MONone; |
| 4107 | if (isVolatile) |
| 4108 | MMOFlags |= MachineMemOperand::MOVolatile; |
| 4109 | if (isNonTemporal) |
| 4110 | MMOFlags |= MachineMemOperand::MONonTemporal; |
| 4111 | if (isInvariant) |
| 4112 | MMOFlags |= MachineMemOperand::MOInvariant; |
| 4113 | if (isDereferenceable) |
| 4114 | MMOFlags |= MachineMemOperand::MODereferenceable; |
| 4115 | MMOFlags |= TLI.getMMOFlags(I); |
| 4116 | |
| 4117 | SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, |
| 4118 | MachinePointerInfo(SV, Offsets[i]), Alignment, |
| 4119 | MMOFlags, AAInfo, Ranges); |
| 4120 | Chains[ChainI] = L.getValue(1); |
| 4121 | |
| 4122 | if (MemVTs[i] != ValueVTs[i]) |
| 4123 | L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); |
| 4124 | |
| 4125 | Values[i] = L; |
| 4126 | } |
| 4127 | |
| 4128 | if (!ConstantMemory) { |
| 4129 | SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, |
| 4130 | makeArrayRef(Chains.data(), ChainI)); |
| 4131 | if (isVolatile) |
| 4132 | DAG.setRoot(Chain); |
| 4133 | else |
| 4134 | PendingLoads.push_back(Chain); |
| 4135 | } |
| 4136 | |
| 4137 | setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, |
| 4138 | DAG.getVTList(ValueVTs), Values)); |
| 4139 | } |
| 4140 | |
| 4141 | void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { |
| 4142 | assert(DAG.getTargetLoweringInfo().supportSwiftError() && |
| 4143 | "call visitStoreToSwiftError when backend supports swifterror" ); |
| 4144 | |
| 4145 | SmallVector<EVT, 4> ValueVTs; |
| 4146 | SmallVector<uint64_t, 4> Offsets; |
| 4147 | const Value *SrcV = I.getOperand(0); |
| 4148 | ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), |
| 4149 | SrcV->getType(), ValueVTs, &Offsets); |
| 4150 | assert(ValueVTs.size() == 1 && Offsets[0] == 0 && |
| 4151 | "expect a single EVT for swifterror" ); |
| 4152 | |
| 4153 | SDValue Src = getValue(SrcV); |
| 4154 | // Create a virtual register, then update the virtual register. |
| 4155 | unsigned VReg = |
| 4156 | SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); |
| 4157 | // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue |
| 4158 | // Chain can be getRoot or getControlRoot. |
| 4159 | SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, |
| 4160 | SDValue(Src.getNode(), Src.getResNo())); |
| 4161 | DAG.setRoot(CopyNode); |
| 4162 | } |
| 4163 | |
| 4164 | void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { |
| 4165 | assert(DAG.getTargetLoweringInfo().supportSwiftError() && |
| 4166 | "call visitLoadFromSwiftError when backend supports swifterror" ); |
| 4167 | |
| 4168 | assert(!I.isVolatile() && |
| 4169 | I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && |
| 4170 | I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && |
| 4171 | "Support volatile, non temporal, invariant for load_from_swift_error" ); |
| 4172 | |
| 4173 | const Value *SV = I.getOperand(0); |
| 4174 | Type *Ty = I.getType(); |
| 4175 | AAMDNodes AAInfo; |
| 4176 | I.getAAMetadata(AAInfo); |
| 4177 | assert( |
| 4178 | (!AA || |
| 4179 | !AA->pointsToConstantMemory(MemoryLocation( |
| 4180 | SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), |
| 4181 | AAInfo))) && |
| 4182 | "load_from_swift_error should not be constant memory" ); |
| 4183 | |
| 4184 | SmallVector<EVT, 4> ValueVTs; |
| 4185 | SmallVector<uint64_t, 4> Offsets; |
| 4186 | ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, |
| 4187 | ValueVTs, &Offsets); |
| 4188 | assert(ValueVTs.size() == 1 && Offsets[0] == 0 && |
| 4189 | "expect a single EVT for swifterror" ); |
| 4190 | |
| 4191 | // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT |
| 4192 | SDValue L = DAG.getCopyFromReg( |
| 4193 | getRoot(), getCurSDLoc(), |
| 4194 | SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); |
| 4195 | |
| 4196 | setValue(&I, L); |
| 4197 | } |
| 4198 | |
| 4199 | void SelectionDAGBuilder::visitStore(const StoreInst &I) { |
| 4200 | if (I.isAtomic()) |
| 4201 | return visitAtomicStore(I); |
| 4202 | |
| 4203 | const Value *SrcV = I.getOperand(0); |
| 4204 | const Value *PtrV = I.getOperand(1); |
| 4205 | |
| 4206 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 4207 | if (TLI.supportSwiftError()) { |
| 4208 | // Swifterror values can come from either a function parameter with |
| 4209 | // swifterror attribute or an alloca with swifterror attribute. |
| 4210 | if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { |
| 4211 | if (Arg->hasSwiftErrorAttr()) |
| 4212 | return visitStoreToSwiftError(I); |
| 4213 | } |
| 4214 | |
| 4215 | if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { |
| 4216 | if (Alloca->isSwiftError()) |
| 4217 | return visitStoreToSwiftError(I); |
| 4218 | } |
| 4219 | } |
| 4220 | |
| 4221 | SmallVector<EVT, 4> ValueVTs, MemVTs; |
| 4222 | SmallVector<uint64_t, 4> Offsets; |
| 4223 | ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), |
| 4224 | SrcV->getType(), ValueVTs, &MemVTs, &Offsets); |
| 4225 | unsigned NumValues = ValueVTs.size(); |
| 4226 | if (NumValues == 0) |
| 4227 | return; |
| 4228 | |
| 4229 | // Get the lowered operands. Note that we do this after |
| 4230 | // checking if NumResults is zero, because with zero results |
| 4231 | // the operands won't have values in the map. |
| 4232 | SDValue Src = getValue(SrcV); |
| 4233 | SDValue Ptr = getValue(PtrV); |
| 4234 | |
| 4235 | SDValue Root = getRoot(); |
| 4236 | SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); |
| 4237 | SDLoc dl = getCurSDLoc(); |
| 4238 | unsigned Alignment = I.getAlignment(); |
| 4239 | AAMDNodes AAInfo; |
| 4240 | I.getAAMetadata(AAInfo); |
| 4241 | |
| 4242 | auto MMOFlags = MachineMemOperand::MONone; |
| 4243 | if (I.isVolatile()) |
| 4244 | MMOFlags |= MachineMemOperand::MOVolatile; |
| 4245 | if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) |
| 4246 | MMOFlags |= MachineMemOperand::MONonTemporal; |
| 4247 | MMOFlags |= TLI.getMMOFlags(I); |
| 4248 | |
| 4249 | // An aggregate load cannot wrap around the address space, so offsets to its |
| 4250 | // parts don't wrap either. |
| 4251 | SDNodeFlags Flags; |
| 4252 | Flags.setNoUnsignedWrap(true); |
| 4253 | |
| 4254 | unsigned ChainI = 0; |
| 4255 | for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { |
| 4256 | // See visitLoad comments. |
| 4257 | if (ChainI == MaxParallelChains) { |
| 4258 | SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, |
| 4259 | makeArrayRef(Chains.data(), ChainI)); |
| 4260 | Root = Chain; |
| 4261 | ChainI = 0; |
| 4262 | } |
| 4263 | SDValue Add = DAG.getPointerAdd(dl, Ptr, Offsets[i], Flags); |
| 4264 | SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); |
| 4265 | if (MemVTs[i] != ValueVTs[i]) |
| 4266 | Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); |
| 4267 | SDValue St = |
| 4268 | DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), |
| 4269 | Alignment, MMOFlags, AAInfo); |
| 4270 | Chains[ChainI] = St; |
| 4271 | } |
| 4272 | |
| 4273 | SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, |
| 4274 | makeArrayRef(Chains.data(), ChainI)); |
| 4275 | DAG.setRoot(StoreNode); |
| 4276 | } |
| 4277 | |
| 4278 | void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, |
| 4279 | bool IsCompressing) { |
| 4280 | SDLoc sdl = getCurSDLoc(); |
| 4281 | |
| 4282 | auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, |
| 4283 | unsigned& Alignment) { |
| 4284 | // llvm.masked.store.*(Src0, Ptr, alignment, Mask) |
| 4285 | Src0 = I.getArgOperand(0); |
| 4286 | Ptr = I.getArgOperand(1); |
| 4287 | Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); |
| 4288 | Mask = I.getArgOperand(3); |
| 4289 | }; |
| 4290 | auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, |
| 4291 | unsigned& Alignment) { |
| 4292 | // llvm.masked.compressstore.*(Src0, Ptr, Mask) |
| 4293 | Src0 = I.getArgOperand(0); |
| 4294 | Ptr = I.getArgOperand(1); |
| 4295 | Mask = I.getArgOperand(2); |
| 4296 | Alignment = 0; |
| 4297 | }; |
| 4298 | |
| 4299 | Value *PtrOperand, *MaskOperand, *Src0Operand; |
| 4300 | unsigned Alignment; |
| 4301 | if (IsCompressing) |
| 4302 | getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); |
| 4303 | else |
| 4304 | getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); |
| 4305 | |
| 4306 | SDValue Ptr = getValue(PtrOperand); |
| 4307 | SDValue Src0 = getValue(Src0Operand); |
| 4308 | SDValue Mask = getValue(MaskOperand); |
| 4309 | |
| 4310 | EVT VT = Src0.getValueType(); |
| 4311 | if (!Alignment) |
| 4312 | Alignment = DAG.getEVTAlignment(VT); |
| 4313 | |
| 4314 | AAMDNodes AAInfo; |
| 4315 | I.getAAMetadata(AAInfo); |
| 4316 | |
| 4317 | MachineMemOperand *MMO = |
| 4318 | DAG.getMachineFunction(). |
| 4319 | getMachineMemOperand(MachinePointerInfo(PtrOperand), |
| 4320 | MachineMemOperand::MOStore, VT.getStoreSize(), |
| 4321 | Alignment, AAInfo); |
| 4322 | SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, |
| 4323 | MMO, false /* Truncating */, |
| 4324 | IsCompressing); |
| 4325 | DAG.setRoot(StoreNode); |
| 4326 | setValue(&I, StoreNode); |
| 4327 | } |
| 4328 | |
| 4329 | // Get a uniform base for the Gather/Scatter intrinsic. |
| 4330 | // The first argument of the Gather/Scatter intrinsic is a vector of pointers. |
| 4331 | // We try to represent it as a base pointer + vector of indices. |
| 4332 | // Usually, the vector of pointers comes from a 'getelementptr' instruction. |
| 4333 | // The first operand of the GEP may be a single pointer or a vector of pointers |
| 4334 | // Example: |
| 4335 | // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind |
| 4336 | // or |
| 4337 | // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind |
| 4338 | // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. |
| 4339 | // |
| 4340 | // When the first GEP operand is a single pointer - it is the uniform base we |
| 4341 | // are looking for. If first operand of the GEP is a splat vector - we |
| 4342 | // extract the splat value and use it as a uniform base. |
| 4343 | // In all other cases the function returns 'false'. |
| 4344 | static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, |
| 4345 | SDValue &Scale, SelectionDAGBuilder* SDB) { |
| 4346 | SelectionDAG& DAG = SDB->DAG; |
| 4347 | LLVMContext &Context = *DAG.getContext(); |
| 4348 | |
| 4349 | assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type" ); |
| 4350 | const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); |
| 4351 | if (!GEP) |
| 4352 | return false; |
| 4353 | |
| 4354 | const Value *GEPPtr = GEP->getPointerOperand(); |
| 4355 | if (!GEPPtr->getType()->isVectorTy()) |
| 4356 | Ptr = GEPPtr; |
| 4357 | else if (!(Ptr = getSplatValue(GEPPtr))) |
| 4358 | return false; |
| 4359 | |
| 4360 | unsigned FinalIndex = GEP->getNumOperands() - 1; |
| 4361 | Value *IndexVal = GEP->getOperand(FinalIndex); |
| 4362 | |
| 4363 | // Ensure all the other indices are 0. |
| 4364 | for (unsigned i = 1; i < FinalIndex; ++i) { |
| 4365 | auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 4366 | if (!C || !C->isZero()) |
| 4367 | return false; |
| 4368 | } |
| 4369 | |
| 4370 | // The operands of the GEP may be defined in another basic block. |
| 4371 | // In this case we'll not find nodes for the operands. |
| 4372 | if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) |
| 4373 | return false; |
| 4374 | |
| 4375 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 4376 | const DataLayout &DL = DAG.getDataLayout(); |
| 4377 | Scale = |
| 4378 | DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), |
| 4379 | SDB->getCurSDLoc(), TLI.getPointerRangeTy(DL)); |
| 4380 | Base = SDB->getValue(Ptr); |
| 4381 | Index = SDB->getValue(IndexVal); |
| 4382 | |
| 4383 | if (!Index.getValueType().isVector()) { |
| 4384 | unsigned GEPWidth = GEP->getType()->getVectorNumElements(); |
| 4385 | EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); |
| 4386 | Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); |
| 4387 | } |
| 4388 | return true; |
| 4389 | } |
| 4390 | |
| 4391 | void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { |
| 4392 | SDLoc sdl = getCurSDLoc(); |
| 4393 | |
| 4394 | // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) |
| 4395 | const Value *Ptr = I.getArgOperand(1); |
| 4396 | SDValue Src0 = getValue(I.getArgOperand(0)); |
| 4397 | SDValue Mask = getValue(I.getArgOperand(3)); |
| 4398 | EVT VT = Src0.getValueType(); |
| 4399 | unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); |
| 4400 | if (!Alignment) |
| 4401 | Alignment = DAG.getEVTAlignment(VT); |
| 4402 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 4403 | |
| 4404 | AAMDNodes AAInfo; |
| 4405 | I.getAAMetadata(AAInfo); |
| 4406 | |
| 4407 | SDValue Base; |
| 4408 | SDValue Index; |
| 4409 | SDValue Scale; |
| 4410 | const Value *BasePtr = Ptr; |
| 4411 | bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); |
| 4412 | |
| 4413 | const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; |
| 4414 | MachineMemOperand *MMO = DAG.getMachineFunction(). |
| 4415 | getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), |
| 4416 | MachineMemOperand::MOStore, VT.getStoreSize(), |
| 4417 | Alignment, AAInfo); |
| 4418 | if (!UniformBase) { |
| 4419 | Base = DAG.getConstant(0, sdl, TLI.getPointerRangeTy(DAG.getDataLayout())); |
| 4420 | Index = getValue(Ptr); |
| 4421 | Scale = DAG.getTargetConstant(1, sdl, |
| 4422 | TLI.getPointerRangeTy(DAG.getDataLayout())); |
| 4423 | } |
| 4424 | SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; |
| 4425 | SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, |
| 4426 | Ops, MMO); |
| 4427 | DAG.setRoot(Scatter); |
| 4428 | setValue(&I, Scatter); |
| 4429 | } |
| 4430 | |
| 4431 | void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { |
| 4432 | SDLoc sdl = getCurSDLoc(); |
| 4433 | |
| 4434 | auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, |
| 4435 | unsigned& Alignment) { |
| 4436 | // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) |
| 4437 | Ptr = I.getArgOperand(0); |
| 4438 | Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); |
| 4439 | Mask = I.getArgOperand(2); |
| 4440 | Src0 = I.getArgOperand(3); |
| 4441 | }; |
| 4442 | auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, |
| 4443 | unsigned& Alignment) { |
| 4444 | // @llvm.masked.expandload.*(Ptr, Mask, Src0) |
| 4445 | Ptr = I.getArgOperand(0); |
| 4446 | Alignment = 0; |
| 4447 | Mask = I.getArgOperand(1); |
| 4448 | Src0 = I.getArgOperand(2); |
| 4449 | }; |
| 4450 | |
| 4451 | Value *PtrOperand, *MaskOperand, *Src0Operand; |
| 4452 | unsigned Alignment; |
| 4453 | if (IsExpanding) |
| 4454 | getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); |
| 4455 | else |
| 4456 | getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); |
| 4457 | |
| 4458 | SDValue Ptr = getValue(PtrOperand); |
| 4459 | SDValue Src0 = getValue(Src0Operand); |
| 4460 | SDValue Mask = getValue(MaskOperand); |
| 4461 | |
| 4462 | EVT VT = Src0.getValueType(); |
| 4463 | if (!Alignment) |
| 4464 | Alignment = DAG.getEVTAlignment(VT); |
| 4465 | |
| 4466 | AAMDNodes AAInfo; |
| 4467 | I.getAAMetadata(AAInfo); |
| 4468 | const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); |
| 4469 | |
| 4470 | // Do not serialize masked loads of constant memory with anything. |
| 4471 | bool AddToChain = |
| 4472 | !AA || !AA->pointsToConstantMemory(MemoryLocation( |
| 4473 | PtrOperand, |
| 4474 | LocationSize::precise( |
| 4475 | DAG.getDataLayout().getTypeStoreSize(I.getType())), |
| 4476 | AAInfo)); |
| 4477 | SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); |
| 4478 | |
| 4479 | MachineMemOperand *MMO = |
| 4480 | DAG.getMachineFunction(). |
| 4481 | getMachineMemOperand(MachinePointerInfo(PtrOperand), |
| 4482 | MachineMemOperand::MOLoad, VT.getStoreSize(), |
| 4483 | Alignment, AAInfo, Ranges); |
| 4484 | |
| 4485 | SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, |
| 4486 | ISD::NON_EXTLOAD, IsExpanding); |
| 4487 | if (AddToChain) |
| 4488 | PendingLoads.push_back(Load.getValue(1)); |
| 4489 | setValue(&I, Load); |
| 4490 | } |
| 4491 | |
| 4492 | void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { |
| 4493 | SDLoc sdl = getCurSDLoc(); |
| 4494 | |
| 4495 | // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) |
| 4496 | const Value *Ptr = I.getArgOperand(0); |
| 4497 | SDValue Src0 = getValue(I.getArgOperand(3)); |
| 4498 | SDValue Mask = getValue(I.getArgOperand(2)); |
| 4499 | |
| 4500 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 4501 | EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 4502 | unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); |
| 4503 | if (!Alignment) |
| 4504 | Alignment = DAG.getEVTAlignment(VT); |
| 4505 | |
| 4506 | AAMDNodes AAInfo; |
| 4507 | I.getAAMetadata(AAInfo); |
| 4508 | const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); |
| 4509 | |
| 4510 | SDValue Root = DAG.getRoot(); |
| 4511 | SDValue Base; |
| 4512 | SDValue Index; |
| 4513 | SDValue Scale; |
| 4514 | const Value *BasePtr = Ptr; |
| 4515 | bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); |
| 4516 | bool ConstantMemory = false; |
| 4517 | if (UniformBase && AA && |
| 4518 | AA->pointsToConstantMemory( |
| 4519 | MemoryLocation(BasePtr, |
| 4520 | LocationSize::precise( |
| 4521 | DAG.getDataLayout().getTypeStoreSize(I.getType())), |
| 4522 | AAInfo))) { |
| 4523 | // Do not serialize (non-volatile) loads of constant memory with anything. |
| 4524 | Root = DAG.getEntryNode(); |
| 4525 | ConstantMemory = true; |
| 4526 | } |
| 4527 | |
| 4528 | MachineMemOperand *MMO = |
| 4529 | DAG.getMachineFunction(). |
| 4530 | getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), |
| 4531 | MachineMemOperand::MOLoad, VT.getStoreSize(), |
| 4532 | Alignment, AAInfo, Ranges); |
| 4533 | |
| 4534 | if (!UniformBase) { |
| 4535 | Base = DAG.getConstant(0, sdl, TLI.getPointerRangeTy(DAG.getDataLayout())); |
| 4536 | Index = getValue(Ptr); |
| 4537 | Scale = DAG.getTargetConstant(1, sdl, |
| 4538 | TLI.getPointerRangeTy(DAG.getDataLayout())); |
| 4539 | } |
| 4540 | SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; |
| 4541 | SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, |
| 4542 | Ops, MMO); |
| 4543 | |
| 4544 | SDValue OutChain = Gather.getValue(1); |
| 4545 | if (!ConstantMemory) |
| 4546 | PendingLoads.push_back(OutChain); |
| 4547 | setValue(&I, Gather); |
| 4548 | } |
| 4549 | |
| 4550 | void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { |
| 4551 | SDLoc dl = getCurSDLoc(); |
| 4552 | AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); |
| 4553 | AtomicOrdering FailureOrdering = I.getFailureOrdering(); |
| 4554 | SyncScope::ID SSID = I.getSyncScopeID(); |
| 4555 | |
| 4556 | SDValue InChain = getRoot(); |
| 4557 | |
| 4558 | MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); |
| 4559 | SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); |
| 4560 | |
| 4561 | auto Alignment = DAG.getEVTAlignment(MemVT); |
| 4562 | |
| 4563 | auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; |
| 4564 | if (I.isVolatile()) |
| 4565 | Flags |= MachineMemOperand::MOVolatile; |
| 4566 | Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); |
| 4567 | |
| 4568 | MachineFunction &MF = DAG.getMachineFunction(); |
| 4569 | MachineMemOperand *MMO = |
| 4570 | MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), |
| 4571 | Flags, MemVT.getStoreSize(), Alignment, |
| 4572 | AAMDNodes(), nullptr, SSID, SuccessOrdering, |
| 4573 | FailureOrdering); |
| 4574 | |
| 4575 | SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, |
| 4576 | dl, MemVT, VTs, InChain, |
| 4577 | getValue(I.getPointerOperand()), |
| 4578 | getValue(I.getCompareOperand()), |
| 4579 | getValue(I.getNewValOperand()), MMO); |
| 4580 | |
| 4581 | SDValue OutChain = L.getValue(2); |
| 4582 | |
| 4583 | setValue(&I, L); |
| 4584 | DAG.setRoot(OutChain); |
| 4585 | } |
| 4586 | |
| 4587 | void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { |
| 4588 | SDLoc dl = getCurSDLoc(); |
| 4589 | ISD::NodeType NT; |
| 4590 | switch (I.getOperation()) { |
| 4591 | default: llvm_unreachable("Unknown atomicrmw operation" ); |
| 4592 | case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; |
| 4593 | case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; |
| 4594 | case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; |
| 4595 | case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; |
| 4596 | case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; |
| 4597 | case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; |
| 4598 | case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; |
| 4599 | case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; |
| 4600 | case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; |
| 4601 | case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; |
| 4602 | case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; |
| 4603 | case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; |
| 4604 | case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; |
| 4605 | } |
| 4606 | AtomicOrdering Ordering = I.getOrdering(); |
| 4607 | SyncScope::ID SSID = I.getSyncScopeID(); |
| 4608 | |
| 4609 | SDValue InChain = getRoot(); |
| 4610 | |
| 4611 | auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); |
| 4612 | auto Alignment = DAG.getEVTAlignment(MemVT); |
| 4613 | |
| 4614 | auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; |
| 4615 | if (I.isVolatile()) |
| 4616 | Flags |= MachineMemOperand::MOVolatile; |
| 4617 | Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); |
| 4618 | |
| 4619 | MachineFunction &MF = DAG.getMachineFunction(); |
| 4620 | MachineMemOperand *MMO = |
| 4621 | MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, |
| 4622 | MemVT.getStoreSize(), Alignment, AAMDNodes(), |
| 4623 | nullptr, SSID, Ordering); |
| 4624 | |
| 4625 | SDValue L = |
| 4626 | DAG.getAtomic(NT, dl, MemVT, InChain, |
| 4627 | getValue(I.getPointerOperand()), getValue(I.getValOperand()), |
| 4628 | MMO); |
| 4629 | |
| 4630 | SDValue OutChain = L.getValue(1); |
| 4631 | |
| 4632 | setValue(&I, L); |
| 4633 | DAG.setRoot(OutChain); |
| 4634 | } |
| 4635 | |
| 4636 | void SelectionDAGBuilder::visitFence(const FenceInst &I) { |
| 4637 | SDLoc dl = getCurSDLoc(); |
| 4638 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 4639 | SDValue Ops[3]; |
| 4640 | Ops[0] = getRoot(); |
| 4641 | Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, |
| 4642 | TLI.getFenceOperandTy(DAG.getDataLayout())); |
| 4643 | Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, |
| 4644 | TLI.getFenceOperandTy(DAG.getDataLayout())); |
| 4645 | DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); |
| 4646 | } |
| 4647 | |
| 4648 | void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { |
| 4649 | SDLoc dl = getCurSDLoc(); |
| 4650 | AtomicOrdering Order = I.getOrdering(); |
| 4651 | SyncScope::ID SSID = I.getSyncScopeID(); |
| 4652 | |
| 4653 | SDValue InChain = getRoot(); |
| 4654 | |
| 4655 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 4656 | EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 4657 | EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); |
| 4658 | |
| 4659 | if (!TLI.supportsUnalignedAtomics() && |
| 4660 | I.getAlignment() < MemVT.getSizeInBits() / 8) |
| 4661 | report_fatal_error("Cannot generate unaligned atomic load" ); |
| 4662 | |
| 4663 | auto Flags = MachineMemOperand::MOLoad; |
| 4664 | if (I.isVolatile()) |
| 4665 | Flags |= MachineMemOperand::MOVolatile; |
| 4666 | if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr) |
| 4667 | Flags |= MachineMemOperand::MOInvariant; |
| 4668 | if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout())) |
| 4669 | Flags |= MachineMemOperand::MODereferenceable; |
| 4670 | |
| 4671 | Flags |= TLI.getMMOFlags(I); |
| 4672 | |
| 4673 | MachineMemOperand *MMO = |
| 4674 | DAG.getMachineFunction(). |
| 4675 | getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), |
| 4676 | Flags, MemVT.getStoreSize(), |
| 4677 | I.getAlignment() ? I.getAlignment() : |
| 4678 | DAG.getEVTAlignment(MemVT), |
| 4679 | AAMDNodes(), nullptr, SSID, Order); |
| 4680 | |
| 4681 | InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); |
| 4682 | SDValue L = |
| 4683 | DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, |
| 4684 | getValue(I.getPointerOperand()), MMO); |
| 4685 | |
| 4686 | SDValue OutChain = L.getValue(1); |
| 4687 | if (MemVT != VT) |
| 4688 | L = DAG.getPtrExtOrTrunc(L, dl, VT); |
| 4689 | |
| 4690 | setValue(&I, L); |
| 4691 | DAG.setRoot(OutChain); |
| 4692 | } |
| 4693 | |
| 4694 | void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { |
| 4695 | SDLoc dl = getCurSDLoc(); |
| 4696 | |
| 4697 | AtomicOrdering Ordering = I.getOrdering(); |
| 4698 | SyncScope::ID SSID = I.getSyncScopeID(); |
| 4699 | |
| 4700 | SDValue InChain = getRoot(); |
| 4701 | |
| 4702 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 4703 | EVT MemVT = |
| 4704 | TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); |
| 4705 | |
| 4706 | if (I.getAlignment() < MemVT.getSizeInBits() / 8) |
| 4707 | report_fatal_error("Cannot generate unaligned atomic store" ); |
| 4708 | |
| 4709 | auto Flags = MachineMemOperand::MOStore; |
| 4710 | if (I.isVolatile()) |
| 4711 | Flags |= MachineMemOperand::MOVolatile; |
| 4712 | Flags |= TLI.getMMOFlags(I); |
| 4713 | |
| 4714 | MachineFunction &MF = DAG.getMachineFunction(); |
| 4715 | MachineMemOperand *MMO = |
| 4716 | MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, |
| 4717 | MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(), |
| 4718 | nullptr, SSID, Ordering); |
| 4719 | |
| 4720 | SDValue Val = getValue(I.getValueOperand()); |
| 4721 | if (Val.getValueType() != MemVT) |
| 4722 | Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); |
| 4723 | |
| 4724 | SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, |
| 4725 | getValue(I.getPointerOperand()), Val, MMO); |
| 4726 | |
| 4727 | |
| 4728 | DAG.setRoot(OutChain); |
| 4729 | } |
| 4730 | |
| 4731 | /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC |
| 4732 | /// node. |
| 4733 | void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, |
| 4734 | unsigned Intrinsic) { |
| 4735 | // Ignore the callsite's attributes. A specific call site may be marked with |
| 4736 | // readnone, but the lowering code will expect the chain based on the |
| 4737 | // definition. |
| 4738 | const Function *F = I.getCalledFunction(); |
| 4739 | bool MayAccessMemory = !F->doesNotAccessMemory(); |
| 4740 | bool HasChain = MayAccessMemory || F->hasSideEffects(); |
| 4741 | bool OnlyLoad = MayAccessMemory && F->onlyReadsMemory(); |
| 4742 | |
| 4743 | // Build the operand list. |
| 4744 | SmallVector<SDValue, 8> Ops; |
| 4745 | if (HasChain) { // If this intrinsic has side-effects, chainify it. |
| 4746 | if (OnlyLoad) { |
| 4747 | // We don't need to serialize loads against other loads. |
| 4748 | Ops.push_back(DAG.getRoot()); |
| 4749 | } else { |
| 4750 | Ops.push_back(getRoot()); |
| 4751 | } |
| 4752 | } |
| 4753 | |
| 4754 | // Info is set by getTgtMemInstrinsic |
| 4755 | TargetLowering::IntrinsicInfo Info; |
| 4756 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 4757 | bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, |
| 4758 | DAG.getMachineFunction(), |
| 4759 | Intrinsic); |
| 4760 | |
| 4761 | // Add the intrinsic ID as an integer operand if it's not a target intrinsic. |
| 4762 | if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || |
| 4763 | Info.opc == ISD::INTRINSIC_W_CHAIN) |
| 4764 | Ops.push_back(DAG.getTargetConstant( |
| 4765 | Intrinsic, getCurSDLoc(), TLI.getPointerRangeTy(DAG.getDataLayout()))); |
| 4766 | |
| 4767 | // Add all operands of the call to the operand list. |
| 4768 | for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { |
| 4769 | SDValue Op = getValue(I.getArgOperand(i)); |
| 4770 | Ops.push_back(Op); |
| 4771 | } |
| 4772 | |
| 4773 | SmallVector<EVT, 4> ValueVTs; |
| 4774 | ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); |
| 4775 | |
| 4776 | if (HasChain) |
| 4777 | ValueVTs.push_back(MVT::Other); |
| 4778 | |
| 4779 | SDVTList VTs = DAG.getVTList(ValueVTs); |
| 4780 | |
| 4781 | // Create the node. |
| 4782 | SDValue Result; |
| 4783 | if (IsTgtIntrinsic) { |
| 4784 | // This is target intrinsic that touches memory |
| 4785 | Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, |
| 4786 | Ops, Info.memVT, |
| 4787 | MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, |
| 4788 | Info.flags, Info.size); |
| 4789 | } else if (!HasChain) { |
| 4790 | Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); |
| 4791 | } else if (!I.getType()->isVoidTy()) { |
| 4792 | Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); |
| 4793 | } else { |
| 4794 | Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); |
| 4795 | } |
| 4796 | |
| 4797 | if (HasChain) { |
| 4798 | SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); |
| 4799 | if (OnlyLoad) |
| 4800 | PendingLoads.push_back(Chain); |
| 4801 | else |
| 4802 | DAG.setRoot(Chain); |
| 4803 | } |
| 4804 | |
| 4805 | if (!I.getType()->isVoidTy()) { |
| 4806 | if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { |
| 4807 | EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); |
| 4808 | Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); |
| 4809 | } else |
| 4810 | Result = lowerRangeToAssertZExt(DAG, I, Result); |
| 4811 | |
| 4812 | setValue(&I, Result); |
| 4813 | } |
| 4814 | } |
| 4815 | |
| 4816 | /// GetSignificand - Get the significand and build it into a floating-point |
| 4817 | /// number with exponent of 1: |
| 4818 | /// |
| 4819 | /// Op = (Op & 0x007fffff) | 0x3f800000; |
| 4820 | /// |
| 4821 | /// where Op is the hexadecimal representation of floating point value. |
| 4822 | static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { |
| 4823 | SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, |
| 4824 | DAG.getConstant(0x007fffff, dl, MVT::i32)); |
| 4825 | SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, |
| 4826 | DAG.getConstant(0x3f800000, dl, MVT::i32)); |
| 4827 | return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); |
| 4828 | } |
| 4829 | |
| 4830 | /// GetExponent - Get the exponent: |
| 4831 | /// |
| 4832 | /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); |
| 4833 | /// |
| 4834 | /// where Op is the hexadecimal representation of floating point value. |
| 4835 | static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, |
| 4836 | const TargetLowering &TLI, const SDLoc &dl) { |
| 4837 | SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, |
| 4838 | DAG.getConstant(0x7f800000, dl, MVT::i32)); |
| 4839 | SDValue t1 = DAG.getNode( |
| 4840 | ISD::SRL, dl, MVT::i32, t0, |
| 4841 | DAG.getConstant(23, dl, TLI.getPointerRangeTy(DAG.getDataLayout()))); |
| 4842 | SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, |
| 4843 | DAG.getConstant(127, dl, MVT::i32)); |
| 4844 | return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); |
| 4845 | } |
| 4846 | |
| 4847 | /// getF32Constant - Get 32-bit floating point constant. |
| 4848 | static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, |
| 4849 | const SDLoc &dl) { |
| 4850 | return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, |
| 4851 | MVT::f32); |
| 4852 | } |
| 4853 | |
| 4854 | static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, |
| 4855 | SelectionDAG &DAG) { |
| 4856 | // TODO: What fast-math-flags should be set on the floating-point nodes? |
| 4857 | |
| 4858 | // IntegerPartOfX = ((int32_t)(t0); |
| 4859 | SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); |
| 4860 | |
| 4861 | // FractionalPartOfX = t0 - (float)IntegerPartOfX; |
| 4862 | SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); |
| 4863 | SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); |
| 4864 | |
| 4865 | // IntegerPartOfX <<= 23; |
| 4866 | IntegerPartOfX = |
| 4867 | DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, |
| 4868 | DAG.getConstant(23, dl, |
| 4869 | DAG.getTargetLoweringInfo().getPointerRangeTy( |
| 4870 | DAG.getDataLayout()))); |
| 4871 | |
| 4872 | SDValue TwoToFractionalPartOfX; |
| 4873 | if (LimitFloatPrecision <= 6) { |
| 4874 | // For floating-point precision of 6: |
| 4875 | // |
| 4876 | // TwoToFractionalPartOfX = |
| 4877 | // 0.997535578f + |
| 4878 | // (0.735607626f + 0.252464424f * x) * x; |
| 4879 | // |
| 4880 | // error 0.0144103317, which is 6 bits |
| 4881 | SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, |
| 4882 | getF32Constant(DAG, 0x3e814304, dl)); |
| 4883 | SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, |
| 4884 | getF32Constant(DAG, 0x3f3c50c8, dl)); |
| 4885 | SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); |
| 4886 | TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, |
| 4887 | getF32Constant(DAG, 0x3f7f5e7e, dl)); |
| 4888 | } else if (LimitFloatPrecision <= 12) { |
| 4889 | // For floating-point precision of 12: |
| 4890 | // |
| 4891 | // TwoToFractionalPartOfX = |
| 4892 | // 0.999892986f + |
| 4893 | // (0.696457318f + |
| 4894 | // (0.224338339f + 0.792043434e-1f * x) * x) * x; |
| 4895 | // |
| 4896 | // error 0.000107046256, which is 13 to 14 bits |
| 4897 | SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, |
| 4898 | getF32Constant(DAG, 0x3da235e3, dl)); |
| 4899 | SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, |
| 4900 | getF32Constant(DAG, 0x3e65b8f3, dl)); |
| 4901 | SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); |
| 4902 | SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, |
| 4903 | getF32Constant(DAG, 0x3f324b07, dl)); |
| 4904 | SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); |
| 4905 | TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, |
| 4906 | getF32Constant(DAG, 0x3f7ff8fd, dl)); |
| 4907 | } else { // LimitFloatPrecision <= 18 |
| 4908 | // For floating-point precision of 18: |
| 4909 | // |
| 4910 | // TwoToFractionalPartOfX = |
| 4911 | // 0.999999982f + |
| 4912 | // (0.693148872f + |
| 4913 | // (0.240227044f + |
| 4914 | // (0.554906021e-1f + |
| 4915 | // (0.961591928e-2f + |
| 4916 | // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; |
| 4917 | // error 2.47208000*10^(-7), which is better than 18 bits |
| 4918 | SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, |
| 4919 | getF32Constant(DAG, 0x3924b03e, dl)); |
| 4920 | SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, |
| 4921 | getF32Constant(DAG, 0x3ab24b87, dl)); |
| 4922 | SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); |
| 4923 | SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, |
| 4924 | getF32Constant(DAG, 0x3c1d8c17, dl)); |
| 4925 | SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); |
| 4926 | SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, |
| 4927 | getF32Constant(DAG, 0x3d634a1d, dl)); |
| 4928 | SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); |
| 4929 | SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, |
| 4930 | getF32Constant(DAG, 0x3e75fe14, dl)); |
| 4931 | SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); |
| 4932 | SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, |
| 4933 | getF32Constant(DAG, 0x3f317234, dl)); |
| 4934 | SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); |
| 4935 | TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, |
| 4936 | getF32Constant(DAG, 0x3f800000, dl)); |
| 4937 | } |
| 4938 | |
| 4939 | // Add the exponent into the result in integer domain. |
| 4940 | SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); |
| 4941 | return DAG.getNode(ISD::BITCAST, dl, MVT::f32, |
| 4942 | DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); |
| 4943 | } |
| 4944 | |
| 4945 | /// expandExp - Lower an exp intrinsic. Handles the special sequences for |
| 4946 | /// limited-precision mode. |
| 4947 | static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, |
| 4948 | const TargetLowering &TLI) { |
| 4949 | if (Op.getValueType() == MVT::f32 && |
| 4950 | LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { |
| 4951 | |
| 4952 | // Put the exponent in the right bit position for later addition to the |
| 4953 | // final result: |
| 4954 | // |
| 4955 | // #define LOG2OFe 1.4426950f |
| 4956 | // t0 = Op * LOG2OFe |
| 4957 | |
| 4958 | // TODO: What fast-math-flags should be set here? |
| 4959 | SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, |
| 4960 | getF32Constant(DAG, 0x3fb8aa3b, dl)); |
| 4961 | return getLimitedPrecisionExp2(t0, dl, DAG); |
| 4962 | } |
| 4963 | |
| 4964 | // No special expansion. |
| 4965 | return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); |
| 4966 | } |
| 4967 | |
| 4968 | /// expandLog - Lower a log intrinsic. Handles the special sequences for |
| 4969 | /// limited-precision mode. |
| 4970 | static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, |
| 4971 | const TargetLowering &TLI) { |
| 4972 | // TODO: What fast-math-flags should be set on the floating-point nodes? |
| 4973 | |
| 4974 | if (Op.getValueType() == MVT::f32 && |
| 4975 | LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { |
| 4976 | SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); |
| 4977 | |
| 4978 | // Scale the exponent by log(2) [0.69314718f]. |
| 4979 | SDValue Exp = GetExponent(DAG, Op1, TLI, dl); |
| 4980 | SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, |
| 4981 | getF32Constant(DAG, 0x3f317218, dl)); |
| 4982 | |
| 4983 | // Get the significand and build it into a floating-point number with |
| 4984 | // exponent of 1. |
| 4985 | SDValue X = GetSignificand(DAG, Op1, dl); |
| 4986 | |
| 4987 | SDValue LogOfMantissa; |
| 4988 | if (LimitFloatPrecision <= 6) { |
| 4989 | // For floating-point precision of 6: |
| 4990 | // |
| 4991 | // LogofMantissa = |
| 4992 | // -1.1609546f + |
| 4993 | // (1.4034025f - 0.23903021f * x) * x; |
| 4994 | // |
| 4995 | // error 0.0034276066, which is better than 8 bits |
| 4996 | SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, |
| 4997 | getF32Constant(DAG, 0xbe74c456, dl)); |
| 4998 | SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, |
| 4999 | getF32Constant(DAG, 0x3fb3a2b1, dl)); |
| 5000 | SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); |
| 5001 | LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, |
| 5002 | getF32Constant(DAG, 0x3f949a29, dl)); |
| 5003 | } else if (LimitFloatPrecision <= 12) { |
| 5004 | // For floating-point precision of 12: |
| 5005 | // |
| 5006 | // LogOfMantissa = |
| 5007 | // -1.7417939f + |
| 5008 | // (2.8212026f + |
| 5009 | // (-1.4699568f + |
| 5010 | // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; |
| 5011 | // |
| 5012 | // error 0.000061011436, which is 14 bits |
| 5013 | SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, |
| 5014 | getF32Constant(DAG, 0xbd67b6d6, dl)); |
| 5015 | SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, |
| 5016 | getF32Constant(DAG, 0x3ee4f4b8, dl)); |
| 5017 | SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); |
| 5018 | SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, |
| 5019 | getF32Constant(DAG, 0x3fbc278b, dl)); |
| 5020 | SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); |
| 5021 | SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, |
| 5022 | getF32Constant(DAG, 0x40348e95, dl)); |
| 5023 | SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); |
| 5024 | LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, |
| 5025 | getF32Constant(DAG, 0x3fdef31a, dl)); |
| 5026 | } else { // LimitFloatPrecision <= 18 |
| 5027 | // For floating-point precision of 18: |
| 5028 | // |
| 5029 | // LogOfMantissa = |
| 5030 | // -2.1072184f + |
| 5031 | // (4.2372794f + |
| 5032 | // (-3.7029485f + |
| 5033 | // (2.2781945f + |
| 5034 | // (-0.87823314f + |
| 5035 | // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; |
| 5036 | // |
| 5037 | // error 0.0000023660568, which is better than 18 bits |
| 5038 | SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, |
| 5039 | getF32Constant(DAG, 0xbc91e5ac, dl)); |
| 5040 | SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, |
| 5041 | getF32Constant(DAG, 0x3e4350aa, dl)); |
| 5042 | SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); |
| 5043 | SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, |
| 5044 | getF32Constant(DAG, 0x3f60d3e3, dl)); |
| 5045 | SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); |
| 5046 | SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, |
| 5047 | getF32Constant(DAG, 0x4011cdf0, dl)); |
| 5048 | SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); |
| 5049 | SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, |
| 5050 | getF32Constant(DAG, 0x406cfd1c, dl)); |
| 5051 | SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); |
| 5052 | SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, |
| 5053 | getF32Constant(DAG, 0x408797cb, dl)); |
| 5054 | SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); |
| 5055 | LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, |
| 5056 | getF32Constant(DAG, 0x4006dcab, dl)); |
| 5057 | } |
| 5058 | |
| 5059 | return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); |
| 5060 | } |
| 5061 | |
| 5062 | // No special expansion. |
| 5063 | return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); |
| 5064 | } |
| 5065 | |
| 5066 | /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for |
| 5067 | /// limited-precision mode. |
| 5068 | static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, |
| 5069 | const TargetLowering &TLI) { |
| 5070 | // TODO: What fast-math-flags should be set on the floating-point nodes? |
| 5071 | |
| 5072 | if (Op.getValueType() == MVT::f32 && |
| 5073 | LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { |
| 5074 | SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); |
| 5075 | |
| 5076 | // Get the exponent. |
| 5077 | SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); |
| 5078 | |
| 5079 | // Get the significand and build it into a floating-point number with |
| 5080 | // exponent of 1. |
| 5081 | SDValue X = GetSignificand(DAG, Op1, dl); |
| 5082 | |
| 5083 | // Different possible minimax approximations of significand in |
| 5084 | // floating-point for various degrees of accuracy over [1,2]. |
| 5085 | SDValue Log2ofMantissa; |
| 5086 | if (LimitFloatPrecision <= 6) { |
| 5087 | // For floating-point precision of 6: |
| 5088 | // |
| 5089 | // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; |
| 5090 | // |
| 5091 | // error 0.0049451742, which is more than 7 bits |
| 5092 | SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, |
| 5093 | getF32Constant(DAG, 0xbeb08fe0, dl)); |
| 5094 | SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, |
| 5095 | getF32Constant(DAG, 0x40019463, dl)); |
| 5096 | SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); |
| 5097 | Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, |
| 5098 | getF32Constant(DAG, 0x3fd6633d, dl)); |
| 5099 | } else if (LimitFloatPrecision <= 12) { |
| 5100 | // For floating-point precision of 12: |
| 5101 | // |
| 5102 | // Log2ofMantissa = |
| 5103 | // -2.51285454f + |
| 5104 | // (4.07009056f + |
| 5105 | // (-2.12067489f + |
| 5106 | // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; |
| 5107 | // |
| 5108 | // error 0.0000876136000, which is better than 13 bits |
| 5109 | SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, |
| 5110 | getF32Constant(DAG, 0xbda7262e, dl)); |
| 5111 | SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, |
| 5112 | getF32Constant(DAG, 0x3f25280b, dl)); |
| 5113 | SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); |
| 5114 | SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, |
| 5115 | getF32Constant(DAG, 0x4007b923, dl)); |
| 5116 | SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); |
| 5117 | SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, |
| 5118 | getF32Constant(DAG, 0x40823e2f, dl)); |
| 5119 | SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); |
| 5120 | Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, |
| 5121 | getF32Constant(DAG, 0x4020d29c, dl)); |
| 5122 | } else { // LimitFloatPrecision <= 18 |
| 5123 | // For floating-point precision of 18: |
| 5124 | // |
| 5125 | // Log2ofMantissa = |
| 5126 | // -3.0400495f + |
| 5127 | // (6.1129976f + |
| 5128 | // (-5.3420409f + |
| 5129 | // (3.2865683f + |
| 5130 | // (-1.2669343f + |
| 5131 | // (0.27515199f - |
| 5132 | // 0.25691327e-1f * x) * x) * x) * x) * x) * x; |
| 5133 | // |
| 5134 | // error 0.0000018516, which is better than 18 bits |
| 5135 | SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, |
| 5136 | getF32Constant(DAG, 0xbcd2769e, dl)); |
| 5137 | SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, |
| 5138 | getF32Constant(DAG, 0x3e8ce0b9, dl)); |
| 5139 | SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); |
| 5140 | SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, |
| 5141 | getF32Constant(DAG, 0x3fa22ae7, dl)); |
| 5142 | SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); |
| 5143 | SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, |
| 5144 | getF32Constant(DAG, 0x40525723, dl)); |
| 5145 | SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); |
| 5146 | SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, |
| 5147 | getF32Constant(DAG, 0x40aaf200, dl)); |
| 5148 | SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); |
| 5149 | SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, |
| 5150 | getF32Constant(DAG, 0x40c39dad, dl)); |
| 5151 | SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); |
| 5152 | Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, |
| 5153 | getF32Constant(DAG, 0x4042902c, dl)); |
| 5154 | } |
| 5155 | |
| 5156 | return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); |
| 5157 | } |
| 5158 | |
| 5159 | // No special expansion. |
| 5160 | return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); |
| 5161 | } |
| 5162 | |
| 5163 | /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for |
| 5164 | /// limited-precision mode. |
| 5165 | static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, |
| 5166 | const TargetLowering &TLI) { |
| 5167 | // TODO: What fast-math-flags should be set on the floating-point nodes? |
| 5168 | |
| 5169 | if (Op.getValueType() == MVT::f32 && |
| 5170 | LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { |
| 5171 | SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); |
| 5172 | |
| 5173 | // Scale the exponent by log10(2) [0.30102999f]. |
| 5174 | SDValue Exp = GetExponent(DAG, Op1, TLI, dl); |
| 5175 | SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, |
| 5176 | getF32Constant(DAG, 0x3e9a209a, dl)); |
| 5177 | |
| 5178 | // Get the significand and build it into a floating-point number with |
| 5179 | // exponent of 1. |
| 5180 | SDValue X = GetSignificand(DAG, Op1, dl); |
| 5181 | |
| 5182 | SDValue Log10ofMantissa; |
| 5183 | if (LimitFloatPrecision <= 6) { |
| 5184 | // For floating-point precision of 6: |
| 5185 | // |
| 5186 | // Log10ofMantissa = |
| 5187 | // -0.50419619f + |
| 5188 | // (0.60948995f - 0.10380950f * x) * x; |
| 5189 | // |
| 5190 | // error 0.0014886165, which is 6 bits |
| 5191 | SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, |
| 5192 | getF32Constant(DAG, 0xbdd49a13, dl)); |
| 5193 | SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, |
| 5194 | getF32Constant(DAG, 0x3f1c0789, dl)); |
| 5195 | SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); |
| 5196 | Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, |
| 5197 | getF32Constant(DAG, 0x3f011300, dl)); |
| 5198 | } else if (LimitFloatPrecision <= 12) { |
| 5199 | // For floating-point precision of 12: |
| 5200 | // |
| 5201 | // Log10ofMantissa = |
| 5202 | // -0.64831180f + |
| 5203 | // (0.91751397f + |
| 5204 | // (-0.31664806f + 0.47637168e-1f * x) * x) * x; |
| 5205 | // |
| 5206 | // error 0.00019228036, which is better than 12 bits |
| 5207 | SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, |
| 5208 | getF32Constant(DAG, 0x3d431f31, dl)); |
| 5209 | SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, |
| 5210 | getF32Constant(DAG, 0x3ea21fb2, dl)); |
| 5211 | SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); |
| 5212 | SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, |
| 5213 | getF32Constant(DAG, 0x3f6ae232, dl)); |
| 5214 | SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); |
| 5215 | Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, |
| 5216 | getF32Constant(DAG, 0x3f25f7c3, dl)); |
| 5217 | } else { // LimitFloatPrecision <= 18 |
| 5218 | // For floating-point precision of 18: |
| 5219 | // |
| 5220 | // Log10ofMantissa = |
| 5221 | // -0.84299375f + |
| 5222 | // (1.5327582f + |
| 5223 | // (-1.0688956f + |
| 5224 | // (0.49102474f + |
| 5225 | // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; |
| 5226 | // |
| 5227 | // error 0.0000037995730, which is better than 18 bits |
| 5228 | SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, |
| 5229 | getF32Constant(DAG, 0x3c5d51ce, dl)); |
| 5230 | SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, |
| 5231 | getF32Constant(DAG, 0x3e00685a, dl)); |
| 5232 | SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); |
| 5233 | SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, |
| 5234 | getF32Constant(DAG, 0x3efb6798, dl)); |
| 5235 | SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); |
| 5236 | SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, |
| 5237 | getF32Constant(DAG, 0x3f88d192, dl)); |
| 5238 | SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); |
| 5239 | SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, |
| 5240 | getF32Constant(DAG, 0x3fc4316c, dl)); |
| 5241 | SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); |
| 5242 | Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, |
| 5243 | getF32Constant(DAG, 0x3f57ce70, dl)); |
| 5244 | } |
| 5245 | |
| 5246 | return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); |
| 5247 | } |
| 5248 | |
| 5249 | // No special expansion. |
| 5250 | return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); |
| 5251 | } |
| 5252 | |
| 5253 | /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for |
| 5254 | /// limited-precision mode. |
| 5255 | static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, |
| 5256 | const TargetLowering &TLI) { |
| 5257 | if (Op.getValueType() == MVT::f32 && |
| 5258 | LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) |
| 5259 | return getLimitedPrecisionExp2(Op, dl, DAG); |
| 5260 | |
| 5261 | // No special expansion. |
| 5262 | return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); |
| 5263 | } |
| 5264 | |
| 5265 | /// visitPow - Lower a pow intrinsic. Handles the special sequences for |
| 5266 | /// limited-precision mode with x == 10.0f. |
| 5267 | static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, |
| 5268 | SelectionDAG &DAG, const TargetLowering &TLI) { |
| 5269 | bool IsExp10 = false; |
| 5270 | if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && |
| 5271 | LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { |
| 5272 | if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { |
| 5273 | APFloat Ten(10.0f); |
| 5274 | IsExp10 = LHSC->isExactlyValue(Ten); |
| 5275 | } |
| 5276 | } |
| 5277 | |
| 5278 | // TODO: What fast-math-flags should be set on the FMUL node? |
| 5279 | if (IsExp10) { |
| 5280 | // Put the exponent in the right bit position for later addition to the |
| 5281 | // final result: |
| 5282 | // |
| 5283 | // #define LOG2OF10 3.3219281f |
| 5284 | // t0 = Op * LOG2OF10; |
| 5285 | SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, |
| 5286 | getF32Constant(DAG, 0x40549a78, dl)); |
| 5287 | return getLimitedPrecisionExp2(t0, dl, DAG); |
| 5288 | } |
| 5289 | |
| 5290 | // No special expansion. |
| 5291 | return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); |
| 5292 | } |
| 5293 | |
| 5294 | /// ExpandPowI - Expand a llvm.powi intrinsic. |
| 5295 | static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, |
| 5296 | SelectionDAG &DAG) { |
| 5297 | // If RHS is a constant, we can expand this out to a multiplication tree, |
| 5298 | // otherwise we end up lowering to a call to __powidf2 (for example). When |
| 5299 | // optimizing for size, we only want to do this if the expansion would produce |
| 5300 | // a small number of multiplies, otherwise we do the full expansion. |
| 5301 | if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { |
| 5302 | // Get the exponent as a positive value. |
| 5303 | unsigned Val = RHSC->getSExtValue(); |
| 5304 | if ((int)Val < 0) Val = -Val; |
| 5305 | |
| 5306 | // powi(x, 0) -> 1.0 |
| 5307 | if (Val == 0) |
| 5308 | return DAG.getConstantFP(1.0, DL, LHS.getValueType()); |
| 5309 | |
| 5310 | const Function &F = DAG.getMachineFunction().getFunction(); |
| 5311 | if (!F.hasOptSize() || |
| 5312 | // If optimizing for size, don't insert too many multiplies. |
| 5313 | // This inserts up to 5 multiplies. |
| 5314 | countPopulation(Val) + Log2_32(Val) < 7) { |
| 5315 | // We use the simple binary decomposition method to generate the multiply |
| 5316 | // sequence. There are more optimal ways to do this (for example, |
| 5317 | // powi(x,15) generates one more multiply than it should), but this has |
| 5318 | // the benefit of being both really simple and much better than a libcall. |
| 5319 | SDValue Res; // Logically starts equal to 1.0 |
| 5320 | SDValue CurSquare = LHS; |
| 5321 | // TODO: Intrinsics should have fast-math-flags that propagate to these |
| 5322 | // nodes. |
| 5323 | while (Val) { |
| 5324 | if (Val & 1) { |
| 5325 | if (Res.getNode()) |
| 5326 | Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); |
| 5327 | else |
| 5328 | Res = CurSquare; // 1.0*CurSquare. |
| 5329 | } |
| 5330 | |
| 5331 | CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), |
| 5332 | CurSquare, CurSquare); |
| 5333 | Val >>= 1; |
| 5334 | } |
| 5335 | |
| 5336 | // If the original was negative, invert the result, producing 1/(x*x*x). |
| 5337 | if (RHSC->getSExtValue() < 0) |
| 5338 | Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), |
| 5339 | DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); |
| 5340 | return Res; |
| 5341 | } |
| 5342 | } |
| 5343 | |
| 5344 | // Otherwise, expand to a libcall. |
| 5345 | return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); |
| 5346 | } |
| 5347 | |
| 5348 | // getUnderlyingArgReg - Find underlying register used for a truncated or |
| 5349 | // bitcasted argument. |
| 5350 | static unsigned getUnderlyingArgReg(const SDValue &N) { |
| 5351 | switch (N.getOpcode()) { |
| 5352 | case ISD::CopyFromReg: |
| 5353 | return cast<RegisterSDNode>(N.getOperand(1))->getReg(); |
| 5354 | case ISD::BITCAST: |
| 5355 | case ISD::AssertZext: |
| 5356 | case ISD::AssertSext: |
| 5357 | case ISD::TRUNCATE: |
| 5358 | return getUnderlyingArgReg(N.getOperand(0)); |
| 5359 | default: |
| 5360 | return 0; |
| 5361 | } |
| 5362 | } |
| 5363 | |
| 5364 | /// If the DbgValueInst is a dbg_value of a function argument, create the |
| 5365 | /// corresponding DBG_VALUE machine instruction for it now. At the end of |
| 5366 | /// instruction selection, they will be inserted to the entry BB. |
| 5367 | bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( |
| 5368 | const Value *V, DILocalVariable *Variable, DIExpression *Expr, |
| 5369 | DILocation *DL, bool IsDbgDeclare, const SDValue &N) { |
| 5370 | const Argument *Arg = dyn_cast<Argument>(V); |
| 5371 | if (!Arg) |
| 5372 | return false; |
| 5373 | |
| 5374 | if (!IsDbgDeclare) { |
| 5375 | // ArgDbgValues are hoisted to the beginning of the entry block. So we |
| 5376 | // should only emit as ArgDbgValue if the dbg.value intrinsic is found in |
| 5377 | // the entry block. |
| 5378 | bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); |
| 5379 | if (!IsInEntryBlock) |
| 5380 | return false; |
| 5381 | |
| 5382 | // ArgDbgValues are hoisted to the beginning of the entry block. So we |
| 5383 | // should only emit as ArgDbgValue if the dbg.value intrinsic describes a |
| 5384 | // variable that also is a param. |
| 5385 | // |
| 5386 | // Although, if we are at the top of the entry block already, we can still |
| 5387 | // emit using ArgDbgValue. This might catch some situations when the |
| 5388 | // dbg.value refers to an argument that isn't used in the entry block, so |
| 5389 | // any CopyToReg node would be optimized out and the only way to express |
| 5390 | // this DBG_VALUE is by using the physical reg (or FI) as done in this |
| 5391 | // method. ArgDbgValues are hoisted to the beginning of the entry block. So |
| 5392 | // we should only emit as ArgDbgValue if the Variable is an argument to the |
| 5393 | // current function, and the dbg.value intrinsic is found in the entry |
| 5394 | // block. |
| 5395 | bool VariableIsFunctionInputArg = Variable->isParameter() && |
| 5396 | !DL->getInlinedAt(); |
| 5397 | bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; |
| 5398 | if (!IsInPrologue && !VariableIsFunctionInputArg) |
| 5399 | return false; |
| 5400 | |
| 5401 | // Here we assume that a function argument on IR level only can be used to |
| 5402 | // describe one input parameter on source level. If we for example have |
| 5403 | // source code like this |
| 5404 | // |
| 5405 | // struct A { long x, y; }; |
| 5406 | // void foo(struct A a, long b) { |
| 5407 | // ... |
| 5408 | // b = a.x; |
| 5409 | // ... |
| 5410 | // } |
| 5411 | // |
| 5412 | // and IR like this |
| 5413 | // |
| 5414 | // define void @foo(i32 %a1, i32 %a2, i32 %b) { |
| 5415 | // entry: |
| 5416 | // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment |
| 5417 | // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment |
| 5418 | // call void @llvm.dbg.value(metadata i32 %b, "b", |
| 5419 | // ... |
| 5420 | // call void @llvm.dbg.value(metadata i32 %a1, "b" |
| 5421 | // ... |
| 5422 | // |
| 5423 | // then the last dbg.value is describing a parameter "b" using a value that |
| 5424 | // is an argument. But since we already has used %a1 to describe a parameter |
| 5425 | // we should not handle that last dbg.value here (that would result in an |
| 5426 | // incorrect hoisting of the DBG_VALUE to the function entry). |
| 5427 | // Notice that we allow one dbg.value per IR level argument, to accomodate |
| 5428 | // for the situation with fragments above. |
| 5429 | if (VariableIsFunctionInputArg) { |
| 5430 | unsigned ArgNo = Arg->getArgNo(); |
| 5431 | if (ArgNo >= FuncInfo.DescribedArgs.size()) |
| 5432 | FuncInfo.DescribedArgs.resize(ArgNo + 1, false); |
| 5433 | else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) |
| 5434 | return false; |
| 5435 | FuncInfo.DescribedArgs.set(ArgNo); |
| 5436 | } |
| 5437 | } |
| 5438 | |
| 5439 | MachineFunction &MF = DAG.getMachineFunction(); |
| 5440 | const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); |
| 5441 | |
| 5442 | bool IsIndirect = false; |
| 5443 | Optional<MachineOperand> Op; |
| 5444 | // Some arguments' frame index is recorded during argument lowering. |
| 5445 | int FI = FuncInfo.getArgumentFrameIndex(Arg); |
| 5446 | if (FI != std::numeric_limits<int>::max()) |
| 5447 | Op = MachineOperand::CreateFI(FI); |
| 5448 | |
| 5449 | if (!Op && N.getNode()) { |
| 5450 | unsigned Reg = getUnderlyingArgReg(N); |
| 5451 | if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { |
| 5452 | MachineRegisterInfo &RegInfo = MF.getRegInfo(); |
| 5453 | unsigned PR = RegInfo.getLiveInPhysReg(Reg); |
| 5454 | if (PR) |
| 5455 | Reg = PR; |
| 5456 | } |
| 5457 | if (Reg) { |
| 5458 | Op = MachineOperand::CreateReg(Reg, false); |
| 5459 | IsIndirect = IsDbgDeclare; |
| 5460 | } |
| 5461 | } |
| 5462 | |
| 5463 | if (!Op && N.getNode()) { |
| 5464 | // Check if frame index is available. |
| 5465 | SDValue LCandidate = peekThroughBitcasts(N); |
| 5466 | if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) |
| 5467 | if (FrameIndexSDNode *FINode = |
| 5468 | dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) |
| 5469 | Op = MachineOperand::CreateFI(FINode->getIndex()); |
| 5470 | } |
| 5471 | |
| 5472 | if (!Op) { |
| 5473 | // Check if ValueMap has reg number. |
| 5474 | DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); |
| 5475 | if (VMI != FuncInfo.ValueMap.end()) { |
| 5476 | const auto &TLI = DAG.getTargetLoweringInfo(); |
| 5477 | RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, |
| 5478 | V->getType(), getABIRegCopyCC(V)); |
| 5479 | if (RFV.occupiesMultipleRegs()) { |
| 5480 | unsigned Offset = 0; |
| 5481 | for (auto RegAndSize : RFV.getRegsAndSizes()) { |
| 5482 | Op = MachineOperand::CreateReg(RegAndSize.first, false); |
| 5483 | auto FragmentExpr = DIExpression::createFragmentExpression( |
| 5484 | Expr, Offset, RegAndSize.second); |
| 5485 | if (!FragmentExpr) |
| 5486 | continue; |
| 5487 | FuncInfo.ArgDbgValues.push_back( |
| 5488 | BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, |
| 5489 | Op->getReg(), Variable, *FragmentExpr)); |
| 5490 | Offset += RegAndSize.second; |
| 5491 | } |
| 5492 | return true; |
| 5493 | } |
| 5494 | Op = MachineOperand::CreateReg(VMI->second, false); |
| 5495 | IsIndirect = IsDbgDeclare; |
| 5496 | } |
| 5497 | } |
| 5498 | |
| 5499 | if (!Op) |
| 5500 | return false; |
| 5501 | |
| 5502 | assert(Variable->isValidLocationForIntrinsic(DL) && |
| 5503 | "Expected inlined-at fields to agree" ); |
| 5504 | IsIndirect = (Op->isReg()) ? IsIndirect : true; |
| 5505 | FuncInfo.ArgDbgValues.push_back( |
| 5506 | BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, |
| 5507 | *Op, Variable, Expr)); |
| 5508 | |
| 5509 | return true; |
| 5510 | } |
| 5511 | |
| 5512 | /// Return the appropriate SDDbgValue based on N. |
| 5513 | SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, |
| 5514 | DILocalVariable *Variable, |
| 5515 | DIExpression *Expr, |
| 5516 | const DebugLoc &dl, |
| 5517 | unsigned DbgSDNodeOrder) { |
| 5518 | if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { |
| 5519 | // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe |
| 5520 | // stack slot locations. |
| 5521 | // |
| 5522 | // Consider "int x = 0; int *px = &x;". There are two kinds of interesting |
| 5523 | // debug values here after optimization: |
| 5524 | // |
| 5525 | // dbg.value(i32* %px, !"int *px", !DIExpression()), and |
| 5526 | // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) |
| 5527 | // |
| 5528 | // Both describe the direct values of their associated variables. |
| 5529 | return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), |
| 5530 | /*IsIndirect*/ false, dl, DbgSDNodeOrder); |
| 5531 | } |
| 5532 | return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), |
| 5533 | /*IsIndirect*/ false, dl, DbgSDNodeOrder); |
| 5534 | } |
| 5535 | |
| 5536 | // VisualStudio defines setjmp as _setjmp |
| 5537 | #if defined(_MSC_VER) && defined(setjmp) && \ |
| 5538 | !defined(setjmp_undefined_for_msvc) |
| 5539 | # pragma push_macro("setjmp") |
| 5540 | # undef setjmp |
| 5541 | # define setjmp_undefined_for_msvc |
| 5542 | #endif |
| 5543 | |
| 5544 | static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { |
| 5545 | switch (Intrinsic) { |
| 5546 | case Intrinsic::smul_fix: |
| 5547 | return ISD::SMULFIX; |
| 5548 | case Intrinsic::umul_fix: |
| 5549 | return ISD::UMULFIX; |
| 5550 | default: |
| 5551 | llvm_unreachable("Unhandled fixed point intrinsic" ); |
| 5552 | } |
| 5553 | } |
| 5554 | |
| 5555 | void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, |
| 5556 | const char *FunctionName) { |
| 5557 | assert(FunctionName && "FunctionName must not be nullptr" ); |
| 5558 | auto DL = DAG.getDataLayout(); |
| 5559 | SDValue Callee = DAG.getExternalSymbol( |
| 5560 | FunctionName, |
| 5561 | DAG.getTargetLoweringInfo().getPointerTy(DL, DL.getGlobalsAddressSpace())); |
| 5562 | LowerCallTo(&I, Callee, I.isTailCall()); |
| 5563 | } |
| 5564 | |
| 5565 | /// Lower the call to the specified intrinsic function. |
| 5566 | void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, |
| 5567 | unsigned Intrinsic) { |
| 5568 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 5569 | SDLoc sdl = getCurSDLoc(); |
| 5570 | DebugLoc dl = getCurDebugLoc(); |
| 5571 | SDValue Res; |
| 5572 | |
| 5573 | switch (Intrinsic) { |
| 5574 | default: |
| 5575 | // By default, turn this into a target intrinsic node. |
| 5576 | visitTargetIntrinsic(I, Intrinsic); |
| 5577 | return; |
| 5578 | case Intrinsic::vastart: visitVAStart(I); return; |
| 5579 | case Intrinsic::vaend: visitVAEnd(I); return; |
| 5580 | case Intrinsic::vacopy: visitVACopy(I); return; |
| 5581 | case Intrinsic::returnaddress: |
| 5582 | setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, |
| 5583 | TLI.getPointerTy(DAG.getDataLayout(), |
| 5584 | I.getType()->getPointerAddressSpace()), |
| 5585 | getValue(I.getArgOperand(0)))); |
| 5586 | return; |
| 5587 | case Intrinsic::addressofreturnaddress: |
| 5588 | setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, |
| 5589 | TLI.getPointerTy(DAG.getDataLayout(), |
| 5590 | I.getType()->getPointerAddressSpace()))); |
| 5591 | return; |
| 5592 | case Intrinsic::sponentry: |
| 5593 | setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, |
| 5594 | TLI.getPointerTy( |
| 5595 | DAG.getDataLayout(), |
| 5596 | DAG.getDataLayout().getAllocaAddrSpace()))); |
| 5597 | return; |
| 5598 | case Intrinsic::frameaddress: |
| 5599 | setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, |
| 5600 | TLI.getPointerTy(DAG.getDataLayout(), |
| 5601 | I.getType()->getPointerAddressSpace()), |
| 5602 | getValue(I.getArgOperand(0)))); |
| 5603 | return; |
| 5604 | case Intrinsic::read_register: { |
| 5605 | Value *Reg = I.getArgOperand(0); |
| 5606 | SDValue Chain = getRoot(); |
| 5607 | SDValue RegName = |
| 5608 | DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); |
| 5609 | EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 5610 | Res = DAG.getNode(ISD::READ_REGISTER, sdl, |
| 5611 | DAG.getVTList(VT, MVT::Other), Chain, RegName); |
| 5612 | setValue(&I, Res); |
| 5613 | DAG.setRoot(Res.getValue(1)); |
| 5614 | return; |
| 5615 | } |
| 5616 | case Intrinsic::write_register: { |
| 5617 | Value *Reg = I.getArgOperand(0); |
| 5618 | Value *RegValue = I.getArgOperand(1); |
| 5619 | SDValue Chain = getRoot(); |
| 5620 | SDValue RegName = |
| 5621 | DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); |
| 5622 | DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, |
| 5623 | RegName, getValue(RegValue))); |
| 5624 | return; |
| 5625 | } |
| 5626 | case Intrinsic::setjmp: |
| 5627 | lowerCallToExternalSymbol(I, &"_setjmp" [!TLI.usesUnderscoreSetJmp()]); |
| 5628 | return; |
| 5629 | case Intrinsic::longjmp: |
| 5630 | lowerCallToExternalSymbol(I, &"_longjmp" [!TLI.usesUnderscoreLongJmp()]); |
| 5631 | return; |
| 5632 | case Intrinsic::memcpy: { |
| 5633 | const auto &MCI = cast<MemCpyInst>(I); |
| 5634 | SDValue Op1 = getValue(I.getArgOperand(0)); |
| 5635 | SDValue Op2 = getValue(I.getArgOperand(1)); |
| 5636 | SDValue Op3 = getValue(I.getArgOperand(2)); |
| 5637 | // @llvm.memcpy defines 0 and 1 to both mean no alignment. |
| 5638 | unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); |
| 5639 | unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); |
| 5640 | unsigned Align = MinAlign(DstAlign, SrcAlign); |
| 5641 | bool isVol = MCI.isVolatile(); |
| 5642 | bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); |
| 5643 | // FIXME: Support passing different dest/src alignments to the memcpy DAG |
| 5644 | // node. |
| 5645 | Attribute CopyType = I.getAttribute(AttributeList::FunctionIndex, |
| 5646 | "frontend-memtransfer-type" ); |
| 5647 | SDValue MC = DAG.getMemcpy( |
| 5648 | getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false, isTC, |
| 5649 | I.hasFnAttr("must-preserve-cheri-tags" ), |
| 5650 | MachinePointerInfo(I.getArgOperand(0)), |
| 5651 | MachinePointerInfo(I.getArgOperand(1)), CopyType.getValueAsString()); |
| 5652 | updateDAGForMaybeTailCall(MC); |
| 5653 | return; |
| 5654 | } |
| 5655 | case Intrinsic::memset: { |
| 5656 | const auto &MSI = cast<MemSetInst>(I); |
| 5657 | SDValue Op1 = getValue(I.getArgOperand(0)); |
| 5658 | SDValue Op2 = getValue(I.getArgOperand(1)); |
| 5659 | SDValue Op3 = getValue(I.getArgOperand(2)); |
| 5660 | // @llvm.memset defines 0 and 1 to both mean no alignment. |
| 5661 | unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); |
| 5662 | bool isVol = MSI.isVolatile(); |
| 5663 | bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); |
| 5664 | SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, |
| 5665 | isTC, MachinePointerInfo(I.getArgOperand(0))); |
| 5666 | updateDAGForMaybeTailCall(MS); |
| 5667 | return; |
| 5668 | } |
| 5669 | case Intrinsic::memmove: { |
| 5670 | const auto &MMI = cast<MemMoveInst>(I); |
| 5671 | SDValue Op1 = getValue(I.getArgOperand(0)); |
| 5672 | SDValue Op2 = getValue(I.getArgOperand(1)); |
| 5673 | SDValue Op3 = getValue(I.getArgOperand(2)); |
| 5674 | // @llvm.memmove defines 0 and 1 to both mean no alignment. |
| 5675 | unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); |
| 5676 | unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); |
| 5677 | unsigned Align = MinAlign(DstAlign, SrcAlign); |
| 5678 | bool isVol = MMI.isVolatile(); |
| 5679 | bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); |
| 5680 | Attribute MoveType = I.getAttribute(AttributeList::FunctionIndex, |
| 5681 | "frontend-memtransfer-type" ); |
| 5682 | // FIXME: Support passing different dest/src alignments to the memmove DAG |
| 5683 | // node. |
| 5684 | SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, |
| 5685 | isTC, I.hasFnAttr("must-preserve-cheri-tags" ), |
| 5686 | MachinePointerInfo(I.getArgOperand(0)), |
| 5687 | MachinePointerInfo(I.getArgOperand(1)), |
| 5688 | MoveType.getValueAsString()); |
| 5689 | updateDAGForMaybeTailCall(MM); |
| 5690 | return; |
| 5691 | } |
| 5692 | case Intrinsic::memcpy_element_unordered_atomic: { |
| 5693 | const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); |
| 5694 | SDValue Dst = getValue(MI.getRawDest()); |
| 5695 | SDValue Src = getValue(MI.getRawSource()); |
| 5696 | SDValue Length = getValue(MI.getLength()); |
| 5697 | |
| 5698 | unsigned DstAlign = MI.getDestAlignment(); |
| 5699 | unsigned SrcAlign = MI.getSourceAlignment(); |
| 5700 | Type *LengthTy = MI.getLength()->getType(); |
| 5701 | unsigned ElemSz = MI.getElementSizeInBytes(); |
| 5702 | bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); |
| 5703 | SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, |
| 5704 | SrcAlign, Length, LengthTy, ElemSz, isTC, |
| 5705 | MachinePointerInfo(MI.getRawDest()), |
| 5706 | MachinePointerInfo(MI.getRawSource())); |
| 5707 | updateDAGForMaybeTailCall(MC); |
| 5708 | return; |
| 5709 | } |
| 5710 | case Intrinsic::memmove_element_unordered_atomic: { |
| 5711 | auto &MI = cast<AtomicMemMoveInst>(I); |
| 5712 | SDValue Dst = getValue(MI.getRawDest()); |
| 5713 | SDValue Src = getValue(MI.getRawSource()); |
| 5714 | SDValue Length = getValue(MI.getLength()); |
| 5715 | |
| 5716 | unsigned DstAlign = MI.getDestAlignment(); |
| 5717 | unsigned SrcAlign = MI.getSourceAlignment(); |
| 5718 | Type *LengthTy = MI.getLength()->getType(); |
| 5719 | unsigned ElemSz = MI.getElementSizeInBytes(); |
| 5720 | bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); |
| 5721 | SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, |
| 5722 | SrcAlign, Length, LengthTy, ElemSz, isTC, |
| 5723 | MachinePointerInfo(MI.getRawDest()), |
| 5724 | MachinePointerInfo(MI.getRawSource())); |
| 5725 | updateDAGForMaybeTailCall(MC); |
| 5726 | return; |
| 5727 | } |
| 5728 | case Intrinsic::memset_element_unordered_atomic: { |
| 5729 | auto &MI = cast<AtomicMemSetInst>(I); |
| 5730 | SDValue Dst = getValue(MI.getRawDest()); |
| 5731 | SDValue Val = getValue(MI.getValue()); |
| 5732 | SDValue Length = getValue(MI.getLength()); |
| 5733 | |
| 5734 | unsigned DstAlign = MI.getDestAlignment(); |
| 5735 | Type *LengthTy = MI.getLength()->getType(); |
| 5736 | unsigned ElemSz = MI.getElementSizeInBytes(); |
| 5737 | bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); |
| 5738 | SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, |
| 5739 | LengthTy, ElemSz, isTC, |
| 5740 | MachinePointerInfo(MI.getRawDest())); |
| 5741 | updateDAGForMaybeTailCall(MC); |
| 5742 | return; |
| 5743 | } |
| 5744 | case Intrinsic::dbg_addr: |
| 5745 | case Intrinsic::dbg_declare: { |
| 5746 | const auto &DI = cast<DbgVariableIntrinsic>(I); |
| 5747 | DILocalVariable *Variable = DI.getVariable(); |
| 5748 | DIExpression *Expression = DI.getExpression(); |
| 5749 | dropDanglingDebugInfo(Variable, Expression); |
| 5750 | assert(Variable && "Missing variable" ); |
| 5751 | |
| 5752 | // Check if address has undef value. |
| 5753 | const Value *Address = DI.getVariableLocation(); |
| 5754 | if (!Address || isa<UndefValue>(Address) || |
| 5755 | (Address->use_empty() && !isa<Argument>(Address))) { |
| 5756 | LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n" ); |
| 5757 | return; |
| 5758 | } |
| 5759 | |
| 5760 | bool isParameter = Variable->isParameter() || isa<Argument>(Address); |
| 5761 | |
| 5762 | // Check if this variable can be described by a frame index, typically |
| 5763 | // either as a static alloca or a byval parameter. |
| 5764 | int FI = std::numeric_limits<int>::max(); |
| 5765 | if (const auto *AI = |
| 5766 | dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { |
| 5767 | if (AI->isStaticAlloca()) { |
| 5768 | auto I = FuncInfo.StaticAllocaMap.find(AI); |
| 5769 | if (I != FuncInfo.StaticAllocaMap.end()) |
| 5770 | FI = I->second; |
| 5771 | } |
| 5772 | } else if (const auto *Arg = dyn_cast<Argument>( |
| 5773 | Address->stripInBoundsConstantOffsets())) { |
| 5774 | FI = FuncInfo.getArgumentFrameIndex(Arg); |
| 5775 | } |
| 5776 | |
| 5777 | // llvm.dbg.addr is control dependent and always generates indirect |
| 5778 | // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in |
| 5779 | // the MachineFunction variable table. |
| 5780 | if (FI != std::numeric_limits<int>::max()) { |
| 5781 | if (Intrinsic == Intrinsic::dbg_addr) { |
| 5782 | SDDbgValue *SDV = DAG.getFrameIndexDbgValue( |
| 5783 | Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); |
| 5784 | DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); |
| 5785 | } |
| 5786 | return; |
| 5787 | } |
| 5788 | |
| 5789 | SDValue &N = NodeMap[Address]; |
| 5790 | if (!N.getNode() && isa<Argument>(Address)) |
| 5791 | // Check unused arguments map. |
| 5792 | N = UnusedArgNodeMap[Address]; |
| 5793 | SDDbgValue *SDV; |
| 5794 | if (N.getNode()) { |
| 5795 | if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) |
| 5796 | Address = BCI->getOperand(0); |
| 5797 | // Parameters are handled specially. |
| 5798 | auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); |
| 5799 | if (isParameter && FINode) { |
| 5800 | // Byval parameter. We have a frame index at this point. |
| 5801 | SDV = |
| 5802 | DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), |
| 5803 | /*IsIndirect*/ true, dl, SDNodeOrder); |
| 5804 | } else if (isa<Argument>(Address)) { |
| 5805 | // Address is an argument, so try to emit its dbg value using |
| 5806 | // virtual register info from the FuncInfo.ValueMap. |
| 5807 | EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); |
| 5808 | return; |
| 5809 | } else { |
| 5810 | SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), |
| 5811 | true, dl, SDNodeOrder); |
| 5812 | } |
| 5813 | DAG.AddDbgValue(SDV, N.getNode(), isParameter); |
| 5814 | } else { |
| 5815 | // If Address is an argument then try to emit its dbg value using |
| 5816 | // virtual register info from the FuncInfo.ValueMap. |
| 5817 | if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, |
| 5818 | N)) { |
| 5819 | LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n" ); |
| 5820 | } |
| 5821 | } |
| 5822 | return; |
| 5823 | } |
| 5824 | case Intrinsic::dbg_label: { |
| 5825 | const DbgLabelInst &DI = cast<DbgLabelInst>(I); |
| 5826 | DILabel *Label = DI.getLabel(); |
| 5827 | assert(Label && "Missing label" ); |
| 5828 | |
| 5829 | SDDbgLabel *SDV; |
| 5830 | SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); |
| 5831 | DAG.AddDbgLabel(SDV); |
| 5832 | return; |
| 5833 | } |
| 5834 | case Intrinsic::dbg_value: { |
| 5835 | const DbgValueInst &DI = cast<DbgValueInst>(I); |
| 5836 | assert(DI.getVariable() && "Missing variable" ); |
| 5837 | |
| 5838 | DILocalVariable *Variable = DI.getVariable(); |
| 5839 | DIExpression *Expression = DI.getExpression(); |
| 5840 | dropDanglingDebugInfo(Variable, Expression); |
| 5841 | const Value *V = DI.getValue(); |
| 5842 | if (!V) |
| 5843 | return; |
| 5844 | |
| 5845 | if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), |
| 5846 | SDNodeOrder)) |
| 5847 | return; |
| 5848 | |
| 5849 | // TODO: Dangling debug info will eventually either be resolved or produce |
| 5850 | // an Undef DBG_VALUE. However in the resolution case, a gap may appear |
| 5851 | // between the original dbg.value location and its resolved DBG_VALUE, which |
| 5852 | // we should ideally fill with an extra Undef DBG_VALUE. |
| 5853 | |
| 5854 | DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); |
| 5855 | return; |
| 5856 | } |
| 5857 | |
| 5858 | case Intrinsic::eh_typeid_for: { |
| 5859 | // Find the type id for the given typeinfo. |
| 5860 | GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); |
| 5861 | unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); |
| 5862 | Res = DAG.getConstant(TypeID, sdl, MVT::i32); |
| 5863 | setValue(&I, Res); |
| 5864 | return; |
| 5865 | } |
| 5866 | |
| 5867 | case Intrinsic::eh_return_i32: |
| 5868 | case Intrinsic::eh_return_i64: |
| 5869 | DAG.getMachineFunction().setCallsEHReturn(true); |
| 5870 | DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, |
| 5871 | MVT::Other, |
| 5872 | getControlRoot(), |
| 5873 | getValue(I.getArgOperand(0)), |
| 5874 | getValue(I.getArgOperand(1)))); |
| 5875 | return; |
| 5876 | case Intrinsic::eh_unwind_init: |
| 5877 | DAG.getMachineFunction().setCallsUnwindInit(true); |
| 5878 | return; |
| 5879 | case Intrinsic::eh_dwarf_cfa: |
| 5880 | setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, |
| 5881 | TLI.getPointerRangeTy(DAG.getDataLayout()), |
| 5882 | getValue(I.getArgOperand(0)))); |
| 5883 | return; |
| 5884 | case Intrinsic::eh_sjlj_callsite: { |
| 5885 | MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); |
| 5886 | ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); |
| 5887 | assert(CI && "Non-constant call site value in eh.sjlj.callsite!" ); |
| 5888 | assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!" ); |
| 5889 | |
| 5890 | MMI.setCurrentCallSite(CI->getZExtValue()); |
| 5891 | return; |
| 5892 | } |
| 5893 | case Intrinsic::eh_sjlj_functioncontext: { |
| 5894 | // Get and store the index of the function context. |
| 5895 | MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); |
| 5896 | AllocaInst *FnCtx = |
| 5897 | cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); |
| 5898 | int FI = FuncInfo.StaticAllocaMap[FnCtx]; |
| 5899 | MFI.setFunctionContextIndex(FI); |
| 5900 | return; |
| 5901 | } |
| 5902 | case Intrinsic::eh_sjlj_setjmp: { |
| 5903 | SDValue Ops[2]; |
| 5904 | Ops[0] = getRoot(); |
| 5905 | Ops[1] = getValue(I.getArgOperand(0)); |
| 5906 | SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, |
| 5907 | DAG.getVTList(MVT::i32, MVT::Other), Ops); |
| 5908 | setValue(&I, Op.getValue(0)); |
| 5909 | DAG.setRoot(Op.getValue(1)); |
| 5910 | return; |
| 5911 | } |
| 5912 | case Intrinsic::eh_sjlj_longjmp: |
| 5913 | DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, |
| 5914 | getRoot(), getValue(I.getArgOperand(0)))); |
| 5915 | return; |
| 5916 | case Intrinsic::eh_sjlj_setup_dispatch: |
| 5917 | DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, |
| 5918 | getRoot())); |
| 5919 | return; |
| 5920 | case Intrinsic::masked_gather: |
| 5921 | visitMaskedGather(I); |
| 5922 | return; |
| 5923 | case Intrinsic::masked_load: |
| 5924 | visitMaskedLoad(I); |
| 5925 | return; |
| 5926 | case Intrinsic::masked_scatter: |
| 5927 | visitMaskedScatter(I); |
| 5928 | return; |
| 5929 | case Intrinsic::masked_store: |
| 5930 | visitMaskedStore(I); |
| 5931 | return; |
| 5932 | case Intrinsic::masked_expandload: |
| 5933 | visitMaskedLoad(I, true /* IsExpanding */); |
| 5934 | return; |
| 5935 | case Intrinsic::masked_compressstore: |
| 5936 | visitMaskedStore(I, true /* IsCompressing */); |
| 5937 | return; |
| 5938 | case Intrinsic::x86_mmx_pslli_w: |
| 5939 | case Intrinsic::x86_mmx_pslli_d: |
| 5940 | case Intrinsic::x86_mmx_pslli_q: |
| 5941 | case Intrinsic::x86_mmx_psrli_w: |
| 5942 | case Intrinsic::x86_mmx_psrli_d: |
| 5943 | case Intrinsic::x86_mmx_psrli_q: |
| 5944 | case Intrinsic::x86_mmx_psrai_w: |
| 5945 | case Intrinsic::x86_mmx_psrai_d: { |
| 5946 | SDValue ShAmt = getValue(I.getArgOperand(1)); |
| 5947 | if (isa<ConstantSDNode>(ShAmt)) { |
| 5948 | visitTargetIntrinsic(I, Intrinsic); |
| 5949 | return; |
| 5950 | } |
| 5951 | unsigned NewIntrinsic = 0; |
| 5952 | EVT ShAmtVT = MVT::v2i32; |
| 5953 | switch (Intrinsic) { |
| 5954 | case Intrinsic::x86_mmx_pslli_w: |
| 5955 | NewIntrinsic = Intrinsic::x86_mmx_psll_w; |
| 5956 | break; |
| 5957 | case Intrinsic::x86_mmx_pslli_d: |
| 5958 | NewIntrinsic = Intrinsic::x86_mmx_psll_d; |
| 5959 | break; |
| 5960 | case Intrinsic::x86_mmx_pslli_q: |
| 5961 | NewIntrinsic = Intrinsic::x86_mmx_psll_q; |
| 5962 | break; |
| 5963 | case Intrinsic::x86_mmx_psrli_w: |
| 5964 | NewIntrinsic = Intrinsic::x86_mmx_psrl_w; |
| 5965 | break; |
| 5966 | case Intrinsic::x86_mmx_psrli_d: |
| 5967 | NewIntrinsic = Intrinsic::x86_mmx_psrl_d; |
| 5968 | break; |
| 5969 | case Intrinsic::x86_mmx_psrli_q: |
| 5970 | NewIntrinsic = Intrinsic::x86_mmx_psrl_q; |
| 5971 | break; |
| 5972 | case Intrinsic::x86_mmx_psrai_w: |
| 5973 | NewIntrinsic = Intrinsic::x86_mmx_psra_w; |
| 5974 | break; |
| 5975 | case Intrinsic::x86_mmx_psrai_d: |
| 5976 | NewIntrinsic = Intrinsic::x86_mmx_psra_d; |
| 5977 | break; |
| 5978 | default: llvm_unreachable("Impossible intrinsic" ); // Can't reach here. |
| 5979 | } |
| 5980 | |
| 5981 | // The vector shift intrinsics with scalars uses 32b shift amounts but |
| 5982 | // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits |
| 5983 | // to be zero. |
| 5984 | // We must do this early because v2i32 is not a legal type. |
| 5985 | SDValue ShOps[2]; |
| 5986 | ShOps[0] = ShAmt; |
| 5987 | ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); |
| 5988 | ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); |
| 5989 | EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 5990 | ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); |
| 5991 | Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, |
| 5992 | DAG.getConstant(NewIntrinsic, sdl, MVT::i32), |
| 5993 | getValue(I.getArgOperand(0)), ShAmt); |
| 5994 | setValue(&I, Res); |
| 5995 | return; |
| 5996 | } |
| 5997 | case Intrinsic::powi: |
| 5998 | setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), |
| 5999 | getValue(I.getArgOperand(1)), DAG)); |
| 6000 | return; |
| 6001 | case Intrinsic::log: |
| 6002 | setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); |
| 6003 | return; |
| 6004 | case Intrinsic::log2: |
| 6005 | setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); |
| 6006 | return; |
| 6007 | case Intrinsic::log10: |
| 6008 | setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); |
| 6009 | return; |
| 6010 | case Intrinsic::exp: |
| 6011 | setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); |
| 6012 | return; |
| 6013 | case Intrinsic::exp2: |
| 6014 | setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); |
| 6015 | return; |
| 6016 | case Intrinsic::pow: |
| 6017 | setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), |
| 6018 | getValue(I.getArgOperand(1)), DAG, TLI)); |
| 6019 | return; |
| 6020 | case Intrinsic::sqrt: |
| 6021 | case Intrinsic::fabs: |
| 6022 | case Intrinsic::sin: |
| 6023 | case Intrinsic::cos: |
| 6024 | case Intrinsic::floor: |
| 6025 | case Intrinsic::ceil: |
| 6026 | case Intrinsic::trunc: |
| 6027 | case Intrinsic::rint: |
| 6028 | case Intrinsic::nearbyint: |
| 6029 | case Intrinsic::round: |
| 6030 | case Intrinsic::canonicalize: { |
| 6031 | unsigned Opcode; |
| 6032 | switch (Intrinsic) { |
| 6033 | default: llvm_unreachable("Impossible intrinsic" ); // Can't reach here. |
| 6034 | case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; |
| 6035 | case Intrinsic::fabs: Opcode = ISD::FABS; break; |
| 6036 | case Intrinsic::sin: Opcode = ISD::FSIN; break; |
| 6037 | case Intrinsic::cos: Opcode = ISD::FCOS; break; |
| 6038 | case Intrinsic::floor: Opcode = ISD::FFLOOR; break; |
| 6039 | case Intrinsic::ceil: Opcode = ISD::FCEIL; break; |
| 6040 | case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; |
| 6041 | case Intrinsic::rint: Opcode = ISD::FRINT; break; |
| 6042 | case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; |
| 6043 | case Intrinsic::round: Opcode = ISD::FROUND; break; |
| 6044 | case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; |
| 6045 | } |
| 6046 | |
| 6047 | setValue(&I, DAG.getNode(Opcode, sdl, |
| 6048 | getValue(I.getArgOperand(0)).getValueType(), |
| 6049 | getValue(I.getArgOperand(0)))); |
| 6050 | return; |
| 6051 | } |
| 6052 | case Intrinsic::lround: |
| 6053 | case Intrinsic::llround: |
| 6054 | case Intrinsic::lrint: |
| 6055 | case Intrinsic::llrint: { |
| 6056 | unsigned Opcode; |
| 6057 | switch (Intrinsic) { |
| 6058 | default: llvm_unreachable("Impossible intrinsic" ); // Can't reach here. |
| 6059 | case Intrinsic::lround: Opcode = ISD::LROUND; break; |
| 6060 | case Intrinsic::llround: Opcode = ISD::LLROUND; break; |
| 6061 | case Intrinsic::lrint: Opcode = ISD::LRINT; break; |
| 6062 | case Intrinsic::llrint: Opcode = ISD::LLRINT; break; |
| 6063 | } |
| 6064 | |
| 6065 | EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 6066 | setValue(&I, DAG.getNode(Opcode, sdl, RetVT, |
| 6067 | getValue(I.getArgOperand(0)))); |
| 6068 | return; |
| 6069 | } |
| 6070 | case Intrinsic::minnum: { |
| 6071 | auto VT = getValue(I.getArgOperand(0)).getValueType(); |
| 6072 | unsigned Opc = |
| 6073 | I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) |
| 6074 | ? ISD::FMINIMUM |
| 6075 | : ISD::FMINNUM; |
| 6076 | setValue(&I, DAG.getNode(Opc, sdl, VT, |
| 6077 | getValue(I.getArgOperand(0)), |
| 6078 | getValue(I.getArgOperand(1)))); |
| 6079 | return; |
| 6080 | } |
| 6081 | case Intrinsic::maxnum: { |
| 6082 | auto VT = getValue(I.getArgOperand(0)).getValueType(); |
| 6083 | unsigned Opc = |
| 6084 | I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) |
| 6085 | ? ISD::FMAXIMUM |
| 6086 | : ISD::FMAXNUM; |
| 6087 | setValue(&I, DAG.getNode(Opc, sdl, VT, |
| 6088 | getValue(I.getArgOperand(0)), |
| 6089 | getValue(I.getArgOperand(1)))); |
| 6090 | return; |
| 6091 | } |
| 6092 | case Intrinsic::minimum: |
| 6093 | setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, |
| 6094 | getValue(I.getArgOperand(0)).getValueType(), |
| 6095 | getValue(I.getArgOperand(0)), |
| 6096 | getValue(I.getArgOperand(1)))); |
| 6097 | return; |
| 6098 | case Intrinsic::maximum: |
| 6099 | setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, |
| 6100 | getValue(I.getArgOperand(0)).getValueType(), |
| 6101 | getValue(I.getArgOperand(0)), |
| 6102 | getValue(I.getArgOperand(1)))); |
| 6103 | return; |
| 6104 | case Intrinsic::copysign: |
| 6105 | setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, |
| 6106 | getValue(I.getArgOperand(0)).getValueType(), |
| 6107 | getValue(I.getArgOperand(0)), |
| 6108 | getValue(I.getArgOperand(1)))); |
| 6109 | return; |
| 6110 | case Intrinsic::fma: |
| 6111 | setValue(&I, DAG.getNode(ISD::FMA, sdl, |
| 6112 | getValue(I.getArgOperand(0)).getValueType(), |
| 6113 | getValue(I.getArgOperand(0)), |
| 6114 | getValue(I.getArgOperand(1)), |
| 6115 | getValue(I.getArgOperand(2)))); |
| 6116 | return; |
| 6117 | case Intrinsic::experimental_constrained_fadd: |
| 6118 | case Intrinsic::experimental_constrained_fsub: |
| 6119 | case Intrinsic::experimental_constrained_fmul: |
| 6120 | case Intrinsic::experimental_constrained_fdiv: |
| 6121 | case Intrinsic::experimental_constrained_frem: |
| 6122 | case Intrinsic::experimental_constrained_fma: |
| 6123 | case Intrinsic::experimental_constrained_fptrunc: |
| 6124 | case Intrinsic::experimental_constrained_fpext: |
| 6125 | case Intrinsic::experimental_constrained_sqrt: |
| 6126 | case Intrinsic::experimental_constrained_pow: |
| 6127 | case Intrinsic::experimental_constrained_powi: |
| 6128 | case Intrinsic::experimental_constrained_sin: |
| 6129 | case Intrinsic::experimental_constrained_cos: |
| 6130 | case Intrinsic::experimental_constrained_exp: |
| 6131 | case Intrinsic::experimental_constrained_exp2: |
| 6132 | case Intrinsic::experimental_constrained_log: |
| 6133 | case Intrinsic::experimental_constrained_log10: |
| 6134 | case Intrinsic::experimental_constrained_log2: |
| 6135 | case Intrinsic::experimental_constrained_rint: |
| 6136 | case Intrinsic::experimental_constrained_nearbyint: |
| 6137 | case Intrinsic::experimental_constrained_maxnum: |
| 6138 | case Intrinsic::experimental_constrained_minnum: |
| 6139 | case Intrinsic::experimental_constrained_ceil: |
| 6140 | case Intrinsic::experimental_constrained_floor: |
| 6141 | case Intrinsic::experimental_constrained_round: |
| 6142 | case Intrinsic::experimental_constrained_trunc: |
| 6143 | visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); |
| 6144 | return; |
| 6145 | case Intrinsic::fmuladd: { |
| 6146 | EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 6147 | if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && |
| 6148 | TLI.isFMAFasterThanFMulAndFAdd(VT)) { |
| 6149 | setValue(&I, DAG.getNode(ISD::FMA, sdl, |
| 6150 | getValue(I.getArgOperand(0)).getValueType(), |
| 6151 | getValue(I.getArgOperand(0)), |
| 6152 | getValue(I.getArgOperand(1)), |
| 6153 | getValue(I.getArgOperand(2)))); |
| 6154 | } else { |
| 6155 | // TODO: Intrinsic calls should have fast-math-flags. |
| 6156 | SDValue Mul = DAG.getNode(ISD::FMUL, sdl, |
| 6157 | getValue(I.getArgOperand(0)).getValueType(), |
| 6158 | getValue(I.getArgOperand(0)), |
| 6159 | getValue(I.getArgOperand(1))); |
| 6160 | SDValue Add = DAG.getNode(ISD::FADD, sdl, |
| 6161 | getValue(I.getArgOperand(0)).getValueType(), |
| 6162 | Mul, |
| 6163 | getValue(I.getArgOperand(2))); |
| 6164 | setValue(&I, Add); |
| 6165 | } |
| 6166 | return; |
| 6167 | } |
| 6168 | case Intrinsic::convert_to_fp16: |
| 6169 | setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, |
| 6170 | DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, |
| 6171 | getValue(I.getArgOperand(0)), |
| 6172 | DAG.getTargetConstant(0, sdl, |
| 6173 | MVT::i32)))); |
| 6174 | return; |
| 6175 | case Intrinsic::convert_from_fp16: |
| 6176 | setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, |
| 6177 | TLI.getValueType(DAG.getDataLayout(), I.getType()), |
| 6178 | DAG.getNode(ISD::BITCAST, sdl, MVT::f16, |
| 6179 | getValue(I.getArgOperand(0))))); |
| 6180 | return; |
| 6181 | case Intrinsic::pcmarker: { |
| 6182 | SDValue Tmp = getValue(I.getArgOperand(0)); |
| 6183 | DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); |
| 6184 | return; |
| 6185 | } |
| 6186 | case Intrinsic::readcyclecounter: { |
| 6187 | SDValue Op = getRoot(); |
| 6188 | Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, |
| 6189 | DAG.getVTList(MVT::i64, MVT::Other), Op); |
| 6190 | setValue(&I, Res); |
| 6191 | DAG.setRoot(Res.getValue(1)); |
| 6192 | return; |
| 6193 | } |
| 6194 | case Intrinsic::bitreverse: |
| 6195 | setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, |
| 6196 | getValue(I.getArgOperand(0)).getValueType(), |
| 6197 | getValue(I.getArgOperand(0)))); |
| 6198 | return; |
| 6199 | case Intrinsic::bswap: |
| 6200 | setValue(&I, DAG.getNode(ISD::BSWAP, sdl, |
| 6201 | getValue(I.getArgOperand(0)).getValueType(), |
| 6202 | getValue(I.getArgOperand(0)))); |
| 6203 | return; |
| 6204 | case Intrinsic::cttz: { |
| 6205 | SDValue Arg = getValue(I.getArgOperand(0)); |
| 6206 | ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); |
| 6207 | EVT Ty = Arg.getValueType(); |
| 6208 | setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, |
| 6209 | sdl, Ty, Arg)); |
| 6210 | return; |
| 6211 | } |
| 6212 | case Intrinsic::ctlz: { |
| 6213 | SDValue Arg = getValue(I.getArgOperand(0)); |
| 6214 | ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); |
| 6215 | EVT Ty = Arg.getValueType(); |
| 6216 | setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, |
| 6217 | sdl, Ty, Arg)); |
| 6218 | return; |
| 6219 | } |
| 6220 | case Intrinsic::ctpop: { |
| 6221 | SDValue Arg = getValue(I.getArgOperand(0)); |
| 6222 | EVT Ty = Arg.getValueType(); |
| 6223 | setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); |
| 6224 | return; |
| 6225 | } |
| 6226 | case Intrinsic::fshl: |
| 6227 | case Intrinsic::fshr: { |
| 6228 | bool IsFSHL = Intrinsic == Intrinsic::fshl; |
| 6229 | SDValue X = getValue(I.getArgOperand(0)); |
| 6230 | SDValue Y = getValue(I.getArgOperand(1)); |
| 6231 | SDValue Z = getValue(I.getArgOperand(2)); |
| 6232 | EVT VT = X.getValueType(); |
| 6233 | SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); |
| 6234 | SDValue Zero = DAG.getConstant(0, sdl, VT); |
| 6235 | SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); |
| 6236 | |
| 6237 | auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; |
| 6238 | if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { |
| 6239 | setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); |
| 6240 | return; |
| 6241 | } |
| 6242 | |
| 6243 | // When X == Y, this is rotate. If the data type has a power-of-2 size, we |
| 6244 | // avoid the select that is necessary in the general case to filter out |
| 6245 | // the 0-shift possibility that leads to UB. |
| 6246 | if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { |
| 6247 | auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; |
| 6248 | if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { |
| 6249 | setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); |
| 6250 | return; |
| 6251 | } |
| 6252 | |
| 6253 | // Some targets only rotate one way. Try the opposite direction. |
| 6254 | RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; |
| 6255 | if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { |
| 6256 | // Negate the shift amount because it is safe to ignore the high bits. |
| 6257 | SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); |
| 6258 | setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); |
| 6259 | return; |
| 6260 | } |
| 6261 | |
| 6262 | // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) |
| 6263 | // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) |
| 6264 | SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); |
| 6265 | SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); |
| 6266 | SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); |
| 6267 | SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); |
| 6268 | setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); |
| 6269 | return; |
| 6270 | } |
| 6271 | |
| 6272 | // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) |
| 6273 | // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) |
| 6274 | SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); |
| 6275 | SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); |
| 6276 | SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); |
| 6277 | SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); |
| 6278 | |
| 6279 | // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, |
| 6280 | // and that is undefined. We must compare and select to avoid UB. |
| 6281 | EVT CCVT = MVT::i1; |
| 6282 | if (VT.isVector()) |
| 6283 | CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); |
| 6284 | |
| 6285 | // For fshl, 0-shift returns the 1st arg (X). |
| 6286 | // For fshr, 0-shift returns the 2nd arg (Y). |
| 6287 | SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); |
| 6288 | setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); |
| 6289 | return; |
| 6290 | } |
| 6291 | case Intrinsic::sadd_sat: { |
| 6292 | SDValue Op1 = getValue(I.getArgOperand(0)); |
| 6293 | SDValue Op2 = getValue(I.getArgOperand(1)); |
| 6294 | setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); |
| 6295 | return; |
| 6296 | } |
| 6297 | case Intrinsic::uadd_sat: { |
| 6298 | SDValue Op1 = getValue(I.getArgOperand(0)); |
| 6299 | SDValue Op2 = getValue(I.getArgOperand(1)); |
| 6300 | setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); |
| 6301 | return; |
| 6302 | } |
| 6303 | case Intrinsic::ssub_sat: { |
| 6304 | SDValue Op1 = getValue(I.getArgOperand(0)); |
| 6305 | SDValue Op2 = getValue(I.getArgOperand(1)); |
| 6306 | setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); |
| 6307 | return; |
| 6308 | } |
| 6309 | case Intrinsic::usub_sat: { |
| 6310 | SDValue Op1 = getValue(I.getArgOperand(0)); |
| 6311 | SDValue Op2 = getValue(I.getArgOperand(1)); |
| 6312 | setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); |
| 6313 | return; |
| 6314 | } |
| 6315 | case Intrinsic::smul_fix: |
| 6316 | case Intrinsic::umul_fix: { |
| 6317 | SDValue Op1 = getValue(I.getArgOperand(0)); |
| 6318 | SDValue Op2 = getValue(I.getArgOperand(1)); |
| 6319 | SDValue Op3 = getValue(I.getArgOperand(2)); |
| 6320 | setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, |
| 6321 | Op1.getValueType(), Op1, Op2, Op3)); |
| 6322 | return; |
| 6323 | } |
| 6324 | case Intrinsic::smul_fix_sat: { |
| 6325 | SDValue Op1 = getValue(I.getArgOperand(0)); |
| 6326 | SDValue Op2 = getValue(I.getArgOperand(1)); |
| 6327 | SDValue Op3 = getValue(I.getArgOperand(2)); |
| 6328 | setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, |
| 6329 | Op3)); |
| 6330 | return; |
| 6331 | } |
| 6332 | case Intrinsic::stacksave: { |
| 6333 | SDValue Op = getRoot(); |
| 6334 | unsigned AS = I.getType()->getPointerAddressSpace(); |
| 6335 | Res = DAG.getNode( |
| 6336 | ISD::STACKSAVE, sdl, |
| 6337 | DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout(), AS), MVT::Other), Op); |
| 6338 | setValue(&I, Res); |
| 6339 | DAG.setRoot(Res.getValue(1)); |
| 6340 | return; |
| 6341 | } |
| 6342 | case Intrinsic::stackrestore: |
| 6343 | Res = getValue(I.getArgOperand(0)); |
| 6344 | DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); |
| 6345 | return; |
| 6346 | case Intrinsic::get_dynamic_area_offset: { |
| 6347 | SDValue Op = getRoot(); |
| 6348 | EVT PtrTy = TLI.getPointerRangeTy(DAG.getDataLayout()); |
| 6349 | EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 6350 | // Result type for @llvm.get.dynamic.area.offset should match PtrTy for |
| 6351 | // target. |
| 6352 | if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) |
| 6353 | report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" |
| 6354 | " intrinsic!" ); |
| 6355 | Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), |
| 6356 | Op); |
| 6357 | DAG.setRoot(Op); |
| 6358 | setValue(&I, Res); |
| 6359 | return; |
| 6360 | } |
| 6361 | case Intrinsic::stackguard: { |
| 6362 | EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), 0); // FIXME: AS0 okay? |
| 6363 | MachineFunction &MF = DAG.getMachineFunction(); |
| 6364 | const Module &M = *MF.getFunction().getParent(); |
| 6365 | SDValue Chain = getRoot(); |
| 6366 | if (TLI.useLoadStackGuardNode()) { |
| 6367 | Res = getLoadStackGuard(DAG, sdl, Chain); |
| 6368 | } else { |
| 6369 | const Value *Global = TLI.getSDagStackGuard(M); |
| 6370 | unsigned Align = DL->getPrefTypeAlignment(Global->getType()); |
| 6371 | Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), |
| 6372 | MachinePointerInfo(Global, 0), Align, |
| 6373 | MachineMemOperand::MOVolatile); |
| 6374 | } |
| 6375 | if (TLI.useStackGuardXorFP()) |
| 6376 | Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); |
| 6377 | DAG.setRoot(Chain); |
| 6378 | setValue(&I, Res); |
| 6379 | return; |
| 6380 | } |
| 6381 | case Intrinsic::stackprotector: { |
| 6382 | // Emit code into the DAG to store the stack guard onto the stack. |
| 6383 | MachineFunction &MF = DAG.getMachineFunction(); |
| 6384 | MachineFrameInfo &MFI = MF.getFrameInfo(); |
| 6385 | // EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); |
| 6386 | EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); |
| 6387 | SDValue Src, Chain = getRoot(); |
| 6388 | |
| 6389 | if (TLI.useLoadStackGuardNode()) |
| 6390 | Src = getLoadStackGuard(DAG, sdl, Chain); |
| 6391 | else |
| 6392 | Src = getValue(I.getArgOperand(0)); // The guard's value. |
| 6393 | |
| 6394 | AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); |
| 6395 | |
| 6396 | int FI = FuncInfo.StaticAllocaMap[Slot]; |
| 6397 | MFI.setStackProtectorIndex(FI); |
| 6398 | |
| 6399 | SDValue FIN = DAG.getFrameIndex(FI, PtrTy); |
| 6400 | |
| 6401 | // Store the stack protector onto the stack. |
| 6402 | Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( |
| 6403 | DAG.getMachineFunction(), FI), |
| 6404 | /* Alignment = */ 0, MachineMemOperand::MOVolatile); |
| 6405 | setValue(&I, Res); |
| 6406 | DAG.setRoot(Res); |
| 6407 | return; |
| 6408 | } |
| 6409 | case Intrinsic::objectsize: { |
| 6410 | // If we don't know by now, we're never going to know. |
| 6411 | ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); |
| 6412 | |
| 6413 | assert(CI && "Non-constant type in __builtin_object_size?" ); |
| 6414 | |
| 6415 | EVT Ty = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 6416 | if (CI->isZero()) |
| 6417 | Res = DAG.getConstant(-1ULL, sdl, Ty); |
| 6418 | else |
| 6419 | Res = DAG.getConstant(0, sdl, Ty); |
| 6420 | |
| 6421 | setValue(&I, Res); |
| 6422 | return; |
| 6423 | } |
| 6424 | |
| 6425 | case Intrinsic::is_constant: |
| 6426 | // If this wasn't constant-folded away by now, then it's not a |
| 6427 | // constant. |
| 6428 | setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); |
| 6429 | return; |
| 6430 | |
| 6431 | case Intrinsic::annotation: |
| 6432 | case Intrinsic::ptr_annotation: |
| 6433 | case Intrinsic::launder_invariant_group: |
| 6434 | case Intrinsic::strip_invariant_group: |
| 6435 | // Drop the intrinsic, but forward the value |
| 6436 | setValue(&I, getValue(I.getOperand(0))); |
| 6437 | return; |
| 6438 | case Intrinsic::assume: |
| 6439 | case Intrinsic::var_annotation: |
| 6440 | case Intrinsic::sideeffect: |
| 6441 | // Discard annotate attributes, assumptions, and artificial side-effects. |
| 6442 | return; |
| 6443 | |
| 6444 | case Intrinsic::codeview_annotation: { |
| 6445 | // Emit a label associated with this metadata. |
| 6446 | MachineFunction &MF = DAG.getMachineFunction(); |
| 6447 | MCSymbol *Label = |
| 6448 | MF.getMMI().getContext().createTempSymbol("annotation" , true); |
| 6449 | Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); |
| 6450 | MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); |
| 6451 | Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); |
| 6452 | DAG.setRoot(Res); |
| 6453 | return; |
| 6454 | } |
| 6455 | |
| 6456 | case Intrinsic::init_trampoline: { |
| 6457 | const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); |
| 6458 | |
| 6459 | SDValue Ops[6]; |
| 6460 | Ops[0] = getRoot(); |
| 6461 | Ops[1] = getValue(I.getArgOperand(0)); |
| 6462 | Ops[2] = getValue(I.getArgOperand(1)); |
| 6463 | Ops[3] = getValue(I.getArgOperand(2)); |
| 6464 | Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); |
| 6465 | Ops[5] = DAG.getSrcValue(F); |
| 6466 | |
| 6467 | Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); |
| 6468 | |
| 6469 | DAG.setRoot(Res); |
| 6470 | return; |
| 6471 | } |
| 6472 | case Intrinsic::adjust_trampoline: |
| 6473 | setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, |
| 6474 | TLI.getPointerTy( |
| 6475 | DAG.getDataLayout(), |
| 6476 | DAG.getDataLayout().getProgramAddressSpace()), |
| 6477 | getValue(I.getArgOperand(0)))); |
| 6478 | return; |
| 6479 | case Intrinsic::gcroot: { |
| 6480 | assert(DAG.getMachineFunction().getFunction().hasGC() && |
| 6481 | "only valid in functions with gc specified, enforced by Verifier" ); |
| 6482 | assert(GFI && "implied by previous" ); |
| 6483 | const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); |
| 6484 | const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); |
| 6485 | |
| 6486 | FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); |
| 6487 | GFI->addStackRoot(FI->getIndex(), TypeMap); |
| 6488 | return; |
| 6489 | } |
| 6490 | case Intrinsic::gcread: |
| 6491 | case Intrinsic::gcwrite: |
| 6492 | llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!" ); |
| 6493 | case Intrinsic::flt_rounds: |
| 6494 | setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); |
| 6495 | return; |
| 6496 | |
| 6497 | case Intrinsic::expect: |
| 6498 | // Just replace __builtin_expect(exp, c) with EXP. |
| 6499 | setValue(&I, getValue(I.getArgOperand(0))); |
| 6500 | return; |
| 6501 | |
| 6502 | case Intrinsic::debugtrap: |
| 6503 | case Intrinsic::trap: { |
| 6504 | StringRef TrapFuncName = |
| 6505 | I.getAttributes() |
| 6506 | .getAttribute(AttributeList::FunctionIndex, "trap-func-name" ) |
| 6507 | .getValueAsString(); |
| 6508 | if (TrapFuncName.empty()) { |
| 6509 | ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? |
| 6510 | ISD::TRAP : ISD::DEBUGTRAP; |
| 6511 | DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); |
| 6512 | return; |
| 6513 | } |
| 6514 | TargetLowering::ArgListTy Args; |
| 6515 | |
| 6516 | TargetLowering::CallLoweringInfo CLI(DAG); |
| 6517 | CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( |
| 6518 | CallingConv::C, I.getType(), |
| 6519 | DAG.getExternalFunctionSymbol(TrapFuncName.data()), std::move(Args)); |
| 6520 | |
| 6521 | std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); |
| 6522 | DAG.setRoot(Result.second); |
| 6523 | return; |
| 6524 | } |
| 6525 | |
| 6526 | case Intrinsic::uadd_with_overflow: |
| 6527 | case Intrinsic::sadd_with_overflow: |
| 6528 | case Intrinsic::usub_with_overflow: |
| 6529 | case Intrinsic::ssub_with_overflow: |
| 6530 | case Intrinsic::umul_with_overflow: |
| 6531 | case Intrinsic::smul_with_overflow: { |
| 6532 | ISD::NodeType Op; |
| 6533 | switch (Intrinsic) { |
| 6534 | default: llvm_unreachable("Impossible intrinsic" ); // Can't reach here. |
| 6535 | case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; |
| 6536 | case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; |
| 6537 | case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; |
| 6538 | case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; |
| 6539 | case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; |
| 6540 | case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; |
| 6541 | } |
| 6542 | SDValue Op1 = getValue(I.getArgOperand(0)); |
| 6543 | SDValue Op2 = getValue(I.getArgOperand(1)); |
| 6544 | |
| 6545 | EVT ResultVT = Op1.getValueType(); |
| 6546 | EVT OverflowVT = MVT::i1; |
| 6547 | if (ResultVT.isVector()) |
| 6548 | OverflowVT = EVT::getVectorVT( |
| 6549 | *Context, OverflowVT, ResultVT.getVectorNumElements()); |
| 6550 | |
| 6551 | SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); |
| 6552 | setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); |
| 6553 | return; |
| 6554 | } |
| 6555 | case Intrinsic::prefetch: { |
| 6556 | SDValue Ops[5]; |
| 6557 | unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); |
| 6558 | auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; |
| 6559 | Ops[0] = DAG.getRoot(); |
| 6560 | Ops[1] = getValue(I.getArgOperand(0)); |
| 6561 | Ops[2] = getValue(I.getArgOperand(1)); |
| 6562 | Ops[3] = getValue(I.getArgOperand(2)); |
| 6563 | Ops[4] = getValue(I.getArgOperand(3)); |
| 6564 | SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, |
| 6565 | DAG.getVTList(MVT::Other), Ops, |
| 6566 | EVT::getIntegerVT(*Context, 8), |
| 6567 | MachinePointerInfo(I.getArgOperand(0)), |
| 6568 | 0, /* align */ |
| 6569 | Flags); |
| 6570 | |
| 6571 | // Chain the prefetch in parallell with any pending loads, to stay out of |
| 6572 | // the way of later optimizations. |
| 6573 | PendingLoads.push_back(Result); |
| 6574 | Result = getRoot(); |
| 6575 | DAG.setRoot(Result); |
| 6576 | return; |
| 6577 | } |
| 6578 | case Intrinsic::lifetime_start: |
| 6579 | case Intrinsic::lifetime_end: { |
| 6580 | bool IsStart = (Intrinsic == Intrinsic::lifetime_start); |
| 6581 | // Stack coloring is not enabled in O0, discard region information. |
| 6582 | if (TM.getOptLevel() == CodeGenOpt::None) |
| 6583 | return; |
| 6584 | |
| 6585 | const int64_t ObjectSize = |
| 6586 | cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); |
| 6587 | Value *const ObjectPtr = I.getArgOperand(1); |
| 6588 | SmallVector<const Value *, 4> Allocas; |
| 6589 | GetUnderlyingObjects(ObjectPtr, Allocas, *DL); |
| 6590 | |
| 6591 | for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), |
| 6592 | E = Allocas.end(); Object != E; ++Object) { |
| 6593 | const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); |
| 6594 | |
| 6595 | // Could not find an Alloca. |
| 6596 | if (!LifetimeObject) |
| 6597 | continue; |
| 6598 | |
| 6599 | // First check that the Alloca is static, otherwise it won't have a |
| 6600 | // valid frame index. |
| 6601 | auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); |
| 6602 | if (SI == FuncInfo.StaticAllocaMap.end()) |
| 6603 | return; |
| 6604 | |
| 6605 | const int FrameIndex = SI->second; |
| 6606 | int64_t Offset; |
| 6607 | if (GetPointerBaseWithConstantOffset( |
| 6608 | ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) |
| 6609 | Offset = -1; // Cannot determine offset from alloca to lifetime object. |
| 6610 | Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, |
| 6611 | Offset); |
| 6612 | DAG.setRoot(Res); |
| 6613 | } |
| 6614 | return; |
| 6615 | } |
| 6616 | case Intrinsic::invariant_start: |
| 6617 | // Discard region information. |
| 6618 | setValue(&I, DAG.getUNDEF(TLI.getPointerRangeTy(DAG.getDataLayout()))); |
| 6619 | return; |
| 6620 | case Intrinsic::invariant_end: |
| 6621 | // Discard region information. |
| 6622 | return; |
| 6623 | case Intrinsic::clear_cache: |
| 6624 | /// FunctionName may be null. |
| 6625 | if (const char *FunctionName = TLI.getClearCacheBuiltinName()) |
| 6626 | lowerCallToExternalSymbol(I, FunctionName); |
| 6627 | return; |
| 6628 | case Intrinsic::donothing: |
| 6629 | // ignore |
| 6630 | return; |
| 6631 | case Intrinsic::experimental_stackmap: |
| 6632 | visitStackmap(I); |
| 6633 | return; |
| 6634 | case Intrinsic::experimental_patchpoint_void: |
| 6635 | case Intrinsic::experimental_patchpoint_i64: |
| 6636 | visitPatchpoint(&I); |
| 6637 | return; |
| 6638 | case Intrinsic::experimental_gc_statepoint: |
| 6639 | LowerStatepoint(ImmutableStatepoint(&I)); |
| 6640 | return; |
| 6641 | case Intrinsic::experimental_gc_result: |
| 6642 | visitGCResult(cast<GCResultInst>(I)); |
| 6643 | return; |
| 6644 | case Intrinsic::experimental_gc_relocate: |
| 6645 | visitGCRelocate(cast<GCRelocateInst>(I)); |
| 6646 | return; |
| 6647 | case Intrinsic::instrprof_increment: |
| 6648 | llvm_unreachable("instrprof failed to lower an increment" ); |
| 6649 | case Intrinsic::instrprof_value_profile: |
| 6650 | llvm_unreachable("instrprof failed to lower a value profiling call" ); |
| 6651 | case Intrinsic::localescape: { |
| 6652 | MachineFunction &MF = DAG.getMachineFunction(); |
| 6653 | const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); |
| 6654 | |
| 6655 | // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission |
| 6656 | // is the same on all targets. |
| 6657 | for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { |
| 6658 | Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); |
| 6659 | if (isa<ConstantPointerNull>(Arg)) |
| 6660 | continue; // Skip null pointers. They represent a hole in index space. |
| 6661 | AllocaInst *Slot = cast<AllocaInst>(Arg); |
| 6662 | assert(FuncInfo.StaticAllocaMap.count(Slot) && |
| 6663 | "can only escape static allocas" ); |
| 6664 | int FI = FuncInfo.StaticAllocaMap[Slot]; |
| 6665 | MCSymbol *FrameAllocSym = |
| 6666 | MF.getMMI().getContext().getOrCreateFrameAllocSymbol( |
| 6667 | GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); |
| 6668 | BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, |
| 6669 | TII->get(TargetOpcode::LOCAL_ESCAPE)) |
| 6670 | .addSym(FrameAllocSym) |
| 6671 | .addFrameIndex(FI); |
| 6672 | } |
| 6673 | |
| 6674 | return; |
| 6675 | } |
| 6676 | |
| 6677 | case Intrinsic::localrecover: { |
| 6678 | // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) |
| 6679 | MachineFunction &MF = DAG.getMachineFunction(); |
| 6680 | MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); |
| 6681 | |
| 6682 | // Get the symbol that defines the frame offset. |
| 6683 | auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); |
| 6684 | auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); |
| 6685 | unsigned IdxVal = |
| 6686 | unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); |
| 6687 | MCSymbol *FrameAllocSym = |
| 6688 | MF.getMMI().getContext().getOrCreateFrameAllocSymbol( |
| 6689 | GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); |
| 6690 | |
| 6691 | // Create a MCSymbol for the label to avoid any target lowering |
| 6692 | // that would make this PC relative. |
| 6693 | SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); |
| 6694 | SDValue OffsetVal = |
| 6695 | DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); |
| 6696 | |
| 6697 | // Add the offset to the FP. |
| 6698 | Value *FP = I.getArgOperand(1); |
| 6699 | SDValue FPVal = getValue(FP); |
| 6700 | SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); |
| 6701 | setValue(&I, Add); |
| 6702 | |
| 6703 | return; |
| 6704 | } |
| 6705 | |
| 6706 | case Intrinsic::eh_exceptionpointer: |
| 6707 | case Intrinsic::eh_exceptioncode: { |
| 6708 | // Get the exception pointer vreg, copy from it, and resize it to fit. |
| 6709 | const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); |
| 6710 | MVT PtrVT = TLI.getPointerRangeTy(DAG.getDataLayout()); |
| 6711 | if (Intrinsic == Intrinsic::eh_exceptionpointer) |
| 6712 | PtrVT = |
| 6713 | TLI.getPointerTy(DAG.getDataLayout(), TLI.getExceptionPointerAS()); |
| 6714 | const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); |
| 6715 | unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); |
| 6716 | SDValue N = |
| 6717 | DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); |
| 6718 | if (Intrinsic == Intrinsic::eh_exceptioncode) |
| 6719 | N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); |
| 6720 | setValue(&I, N); |
| 6721 | return; |
| 6722 | } |
| 6723 | case Intrinsic::xray_customevent: { |
| 6724 | // Here we want to make sure that the intrinsic behaves as if it has a |
| 6725 | // specific calling convention, and only for x86_64. |
| 6726 | // FIXME: Support other platforms later. |
| 6727 | const auto &Triple = DAG.getTarget().getTargetTriple(); |
| 6728 | if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) |
| 6729 | return; |
| 6730 | |
| 6731 | SDLoc DL = getCurSDLoc(); |
| 6732 | SmallVector<SDValue, 8> Ops; |
| 6733 | |
| 6734 | // We want to say that we always want the arguments in registers. |
| 6735 | SDValue LogEntryVal = getValue(I.getArgOperand(0)); |
| 6736 | SDValue StrSizeVal = getValue(I.getArgOperand(1)); |
| 6737 | SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); |
| 6738 | SDValue Chain = getRoot(); |
| 6739 | Ops.push_back(LogEntryVal); |
| 6740 | Ops.push_back(StrSizeVal); |
| 6741 | Ops.push_back(Chain); |
| 6742 | |
| 6743 | // We need to enforce the calling convention for the callsite, so that |
| 6744 | // argument ordering is enforced correctly, and that register allocation can |
| 6745 | // see that some registers may be assumed clobbered and have to preserve |
| 6746 | // them across calls to the intrinsic. |
| 6747 | MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, |
| 6748 | DL, NodeTys, Ops); |
| 6749 | SDValue patchableNode = SDValue(MN, 0); |
| 6750 | DAG.setRoot(patchableNode); |
| 6751 | setValue(&I, patchableNode); |
| 6752 | return; |
| 6753 | } |
| 6754 | case Intrinsic::xray_typedevent: { |
| 6755 | // Here we want to make sure that the intrinsic behaves as if it has a |
| 6756 | // specific calling convention, and only for x86_64. |
| 6757 | // FIXME: Support other platforms later. |
| 6758 | const auto &Triple = DAG.getTarget().getTargetTriple(); |
| 6759 | if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) |
| 6760 | return; |
| 6761 | |
| 6762 | SDLoc DL = getCurSDLoc(); |
| 6763 | SmallVector<SDValue, 8> Ops; |
| 6764 | |
| 6765 | // We want to say that we always want the arguments in registers. |
| 6766 | // It's unclear to me how manipulating the selection DAG here forces callers |
| 6767 | // to provide arguments in registers instead of on the stack. |
| 6768 | SDValue LogTypeId = getValue(I.getArgOperand(0)); |
| 6769 | SDValue LogEntryVal = getValue(I.getArgOperand(1)); |
| 6770 | SDValue StrSizeVal = getValue(I.getArgOperand(2)); |
| 6771 | SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); |
| 6772 | SDValue Chain = getRoot(); |
| 6773 | Ops.push_back(LogTypeId); |
| 6774 | Ops.push_back(LogEntryVal); |
| 6775 | Ops.push_back(StrSizeVal); |
| 6776 | Ops.push_back(Chain); |
| 6777 | |
| 6778 | // We need to enforce the calling convention for the callsite, so that |
| 6779 | // argument ordering is enforced correctly, and that register allocation can |
| 6780 | // see that some registers may be assumed clobbered and have to preserve |
| 6781 | // them across calls to the intrinsic. |
| 6782 | MachineSDNode *MN = DAG.getMachineNode( |
| 6783 | TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); |
| 6784 | SDValue patchableNode = SDValue(MN, 0); |
| 6785 | DAG.setRoot(patchableNode); |
| 6786 | setValue(&I, patchableNode); |
| 6787 | return; |
| 6788 | } |
| 6789 | case Intrinsic::experimental_deoptimize: |
| 6790 | LowerDeoptimizeCall(&I); |
| 6791 | return; |
| 6792 | |
| 6793 | case Intrinsic::experimental_vector_reduce_v2_fadd: |
| 6794 | case Intrinsic::experimental_vector_reduce_v2_fmul: |
| 6795 | case Intrinsic::experimental_vector_reduce_add: |
| 6796 | case Intrinsic::experimental_vector_reduce_mul: |
| 6797 | case Intrinsic::experimental_vector_reduce_and: |
| 6798 | case Intrinsic::experimental_vector_reduce_or: |
| 6799 | case Intrinsic::experimental_vector_reduce_xor: |
| 6800 | case Intrinsic::experimental_vector_reduce_smax: |
| 6801 | case Intrinsic::experimental_vector_reduce_smin: |
| 6802 | case Intrinsic::experimental_vector_reduce_umax: |
| 6803 | case Intrinsic::experimental_vector_reduce_umin: |
| 6804 | case Intrinsic::experimental_vector_reduce_fmax: |
| 6805 | case Intrinsic::experimental_vector_reduce_fmin: |
| 6806 | visitVectorReduce(I, Intrinsic); |
| 6807 | return; |
| 6808 | |
| 6809 | case Intrinsic::icall_branch_funnel: { |
| 6810 | SmallVector<SDValue, 16> Ops; |
| 6811 | Ops.push_back(DAG.getRoot()); |
| 6812 | Ops.push_back(getValue(I.getArgOperand(0))); |
| 6813 | |
| 6814 | int64_t Offset; |
| 6815 | auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( |
| 6816 | I.getArgOperand(1), Offset, DAG.getDataLayout())); |
| 6817 | if (!Base) |
| 6818 | report_fatal_error( |
| 6819 | "llvm.icall.branch.funnel operand must be a GlobalValue" ); |
| 6820 | Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); |
| 6821 | |
| 6822 | struct BranchFunnelTarget { |
| 6823 | int64_t Offset; |
| 6824 | SDValue Target; |
| 6825 | }; |
| 6826 | SmallVector<BranchFunnelTarget, 8> Targets; |
| 6827 | |
| 6828 | for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { |
| 6829 | auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( |
| 6830 | I.getArgOperand(Op), Offset, DAG.getDataLayout())); |
| 6831 | if (ElemBase != Base) |
| 6832 | report_fatal_error("all llvm.icall.branch.funnel operands must refer " |
| 6833 | "to the same GlobalValue" ); |
| 6834 | |
| 6835 | SDValue Val = getValue(I.getArgOperand(Op + 1)); |
| 6836 | auto *GA = dyn_cast<GlobalAddressSDNode>(Val); |
| 6837 | if (!GA) |
| 6838 | report_fatal_error( |
| 6839 | "llvm.icall.branch.funnel operand must be a GlobalValue" ); |
| 6840 | Targets.push_back({Offset, DAG.getTargetGlobalAddress( |
| 6841 | GA->getGlobal(), getCurSDLoc(), |
| 6842 | Val.getValueType(), GA->getOffset())}); |
| 6843 | } |
| 6844 | llvm::sort(Targets, |
| 6845 | [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { |
| 6846 | return T1.Offset < T2.Offset; |
| 6847 | }); |
| 6848 | |
| 6849 | for (auto &T : Targets) { |
| 6850 | Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); |
| 6851 | Ops.push_back(T.Target); |
| 6852 | } |
| 6853 | |
| 6854 | SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, |
| 6855 | getCurSDLoc(), MVT::Other, Ops), |
| 6856 | 0); |
| 6857 | DAG.setRoot(N); |
| 6858 | setValue(&I, N); |
| 6859 | HasTailCall = true; |
| 6860 | return; |
| 6861 | } |
| 6862 | |
| 6863 | case Intrinsic::wasm_landingpad_index: |
| 6864 | // Information this intrinsic contained has been transferred to |
| 6865 | // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely |
| 6866 | // delete it now. |
| 6867 | return; |
| 6868 | |
| 6869 | case Intrinsic::cheri_cap_address_set: { |
| 6870 | if (TLI.hasCapabilitySetAddress()) { |
| 6871 | visitTargetIntrinsic(I, Intrinsic); |
| 6872 | return; |
| 6873 | } |
| 6874 | // SetAddr($cap, $addr) -> CIncOffset($cap, $addr - GetAddr($cap)) |
| 6875 | SDValue Cap = getValue(I.getArgOperand(0)); |
| 6876 | SDValue Addr = getValue(I.getArgOperand(1)); |
| 6877 | EVT CapVT = Cap.getValueType(); |
| 6878 | EVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); |
| 6879 | SDValue CapAddr = DAG.getNode( |
| 6880 | ISD::INTRINSIC_WO_CHAIN, sdl, PtrVT, |
| 6881 | DAG.getConstant(Intrinsic::cheri_cap_address_get, sdl, PtrVT), Cap); |
| 6882 | SDValue Delta = DAG.getNode(ISD::SUB, sdl, PtrVT, Addr, CapAddr); |
| 6883 | Res = DAG.getNode( |
| 6884 | ISD::INTRINSIC_WO_CHAIN, sdl, CapVT, |
| 6885 | DAG.getConstant(Intrinsic::cheri_cap_offset_increment, sdl, PtrVT), |
| 6886 | Cap, Delta); |
| 6887 | setValue(&I, Res); |
| 6888 | return; |
| 6889 | } |
| 6890 | } |
| 6891 | } |
| 6892 | |
| 6893 | void SelectionDAGBuilder::visitConstrainedFPIntrinsic( |
| 6894 | const ConstrainedFPIntrinsic &FPI) { |
| 6895 | SDLoc sdl = getCurSDLoc(); |
| 6896 | unsigned Opcode; |
| 6897 | switch (FPI.getIntrinsicID()) { |
| 6898 | default: llvm_unreachable("Impossible intrinsic" ); // Can't reach here. |
| 6899 | case Intrinsic::experimental_constrained_fadd: |
| 6900 | Opcode = ISD::STRICT_FADD; |
| 6901 | break; |
| 6902 | case Intrinsic::experimental_constrained_fsub: |
| 6903 | Opcode = ISD::STRICT_FSUB; |
| 6904 | break; |
| 6905 | case Intrinsic::experimental_constrained_fmul: |
| 6906 | Opcode = ISD::STRICT_FMUL; |
| 6907 | break; |
| 6908 | case Intrinsic::experimental_constrained_fdiv: |
| 6909 | Opcode = ISD::STRICT_FDIV; |
| 6910 | break; |
| 6911 | case Intrinsic::experimental_constrained_frem: |
| 6912 | Opcode = ISD::STRICT_FREM; |
| 6913 | break; |
| 6914 | case Intrinsic::experimental_constrained_fma: |
| 6915 | Opcode = ISD::STRICT_FMA; |
| 6916 | break; |
| 6917 | case Intrinsic::experimental_constrained_fptrunc: |
| 6918 | Opcode = ISD::STRICT_FP_ROUND; |
| 6919 | break; |
| 6920 | case Intrinsic::experimental_constrained_fpext: |
| 6921 | Opcode = ISD::STRICT_FP_EXTEND; |
| 6922 | break; |
| 6923 | case Intrinsic::experimental_constrained_sqrt: |
| 6924 | Opcode = ISD::STRICT_FSQRT; |
| 6925 | break; |
| 6926 | case Intrinsic::experimental_constrained_pow: |
| 6927 | Opcode = ISD::STRICT_FPOW; |
| 6928 | break; |
| 6929 | case Intrinsic::experimental_constrained_powi: |
| 6930 | Opcode = ISD::STRICT_FPOWI; |
| 6931 | break; |
| 6932 | case Intrinsic::experimental_constrained_sin: |
| 6933 | Opcode = ISD::STRICT_FSIN; |
| 6934 | break; |
| 6935 | case Intrinsic::experimental_constrained_cos: |
| 6936 | Opcode = ISD::STRICT_FCOS; |
| 6937 | break; |
| 6938 | case Intrinsic::experimental_constrained_exp: |
| 6939 | Opcode = ISD::STRICT_FEXP; |
| 6940 | break; |
| 6941 | case Intrinsic::experimental_constrained_exp2: |
| 6942 | Opcode = ISD::STRICT_FEXP2; |
| 6943 | break; |
| 6944 | case Intrinsic::experimental_constrained_log: |
| 6945 | Opcode = ISD::STRICT_FLOG; |
| 6946 | break; |
| 6947 | case Intrinsic::experimental_constrained_log10: |
| 6948 | Opcode = ISD::STRICT_FLOG10; |
| 6949 | break; |
| 6950 | case Intrinsic::experimental_constrained_log2: |
| 6951 | Opcode = ISD::STRICT_FLOG2; |
| 6952 | break; |
| 6953 | case Intrinsic::experimental_constrained_rint: |
| 6954 | Opcode = ISD::STRICT_FRINT; |
| 6955 | break; |
| 6956 | case Intrinsic::experimental_constrained_nearbyint: |
| 6957 | Opcode = ISD::STRICT_FNEARBYINT; |
| 6958 | break; |
| 6959 | case Intrinsic::experimental_constrained_maxnum: |
| 6960 | Opcode = ISD::STRICT_FMAXNUM; |
| 6961 | break; |
| 6962 | case Intrinsic::experimental_constrained_minnum: |
| 6963 | Opcode = ISD::STRICT_FMINNUM; |
| 6964 | break; |
| 6965 | case Intrinsic::experimental_constrained_ceil: |
| 6966 | Opcode = ISD::STRICT_FCEIL; |
| 6967 | break; |
| 6968 | case Intrinsic::experimental_constrained_floor: |
| 6969 | Opcode = ISD::STRICT_FFLOOR; |
| 6970 | break; |
| 6971 | case Intrinsic::experimental_constrained_round: |
| 6972 | Opcode = ISD::STRICT_FROUND; |
| 6973 | break; |
| 6974 | case Intrinsic::experimental_constrained_trunc: |
| 6975 | Opcode = ISD::STRICT_FTRUNC; |
| 6976 | break; |
| 6977 | } |
| 6978 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 6979 | SDValue Chain = getRoot(); |
| 6980 | SmallVector<EVT, 4> ValueVTs; |
| 6981 | ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); |
| 6982 | ValueVTs.push_back(MVT::Other); // Out chain |
| 6983 | |
| 6984 | SDVTList VTs = DAG.getVTList(ValueVTs); |
| 6985 | SDValue Result; |
| 6986 | if (Opcode == ISD::STRICT_FP_ROUND) |
| 6987 | Result = DAG.getNode(Opcode, sdl, VTs, |
| 6988 | { Chain, getValue(FPI.getArgOperand(0)), |
| 6989 | DAG.getTargetConstant(0, sdl, |
| 6990 | // FIXME: Is 0 correct here? I have no idea why |
| 6991 | // floating point rounding takes a null pointer |
| 6992 | // argument. |
| 6993 | TLI.getPointerTy(DAG.getDataLayout(), 0)) }); |
| 6994 | else if (FPI.isUnaryOp()) |
| 6995 | Result = DAG.getNode(Opcode, sdl, VTs, |
| 6996 | { Chain, getValue(FPI.getArgOperand(0)) }); |
| 6997 | else if (FPI.isTernaryOp()) |
| 6998 | Result = DAG.getNode(Opcode, sdl, VTs, |
| 6999 | { Chain, getValue(FPI.getArgOperand(0)), |
| 7000 | getValue(FPI.getArgOperand(1)), |
| 7001 | getValue(FPI.getArgOperand(2)) }); |
| 7002 | else |
| 7003 | Result = DAG.getNode(Opcode, sdl, VTs, |
| 7004 | { Chain, getValue(FPI.getArgOperand(0)), |
| 7005 | getValue(FPI.getArgOperand(1)) }); |
| 7006 | |
| 7007 | if (FPI.getExceptionBehavior() != |
| 7008 | ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) { |
| 7009 | SDNodeFlags Flags; |
| 7010 | Flags.setFPExcept(true); |
| 7011 | Result->setFlags(Flags); |
| 7012 | } |
| 7013 | |
| 7014 | assert(Result.getNode()->getNumValues() == 2); |
| 7015 | SDValue OutChain = Result.getValue(1); |
| 7016 | DAG.setRoot(OutChain); |
| 7017 | SDValue FPResult = Result.getValue(0); |
| 7018 | setValue(&FPI, FPResult); |
| 7019 | } |
| 7020 | |
| 7021 | std::pair<SDValue, SDValue> |
| 7022 | SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, |
| 7023 | const BasicBlock *EHPadBB) { |
| 7024 | MachineFunction &MF = DAG.getMachineFunction(); |
| 7025 | MachineModuleInfo &MMI = MF.getMMI(); |
| 7026 | MCSymbol *BeginLabel = nullptr; |
| 7027 | |
| 7028 | if (EHPadBB) { |
| 7029 | // Insert a label before the invoke call to mark the try range. This can be |
| 7030 | // used to detect deletion of the invoke via the MachineModuleInfo. |
| 7031 | BeginLabel = MMI.getContext().createTempSymbol(); |
| 7032 | |
| 7033 | // For SjLj, keep track of which landing pads go with which invokes |
| 7034 | // so as to maintain the ordering of pads in the LSDA. |
| 7035 | unsigned CallSiteIndex = MMI.getCurrentCallSite(); |
| 7036 | if (CallSiteIndex) { |
| 7037 | MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); |
| 7038 | LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); |
| 7039 | |
| 7040 | // Now that the call site is handled, stop tracking it. |
| 7041 | MMI.setCurrentCallSite(0); |
| 7042 | } |
| 7043 | |
| 7044 | // Both PendingLoads and PendingExports must be flushed here; |
| 7045 | // this call might not return. |
| 7046 | (void)getRoot(); |
| 7047 | DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); |
| 7048 | |
| 7049 | CLI.setChain(getRoot()); |
| 7050 | } |
| 7051 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 7052 | std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); |
| 7053 | |
| 7054 | assert((CLI.IsTailCall || Result.second.getNode()) && |
| 7055 | "Non-null chain expected with non-tail call!" ); |
| 7056 | assert((Result.second.getNode() || !Result.first.getNode()) && |
| 7057 | "Null value expected with tail call!" ); |
| 7058 | |
| 7059 | if (!Result.second.getNode()) { |
| 7060 | // As a special case, a null chain means that a tail call has been emitted |
| 7061 | // and the DAG root is already updated. |
| 7062 | HasTailCall = true; |
| 7063 | |
| 7064 | // Since there's no actual continuation from this block, nothing can be |
| 7065 | // relying on us setting vregs for them. |
| 7066 | PendingExports.clear(); |
| 7067 | } else { |
| 7068 | DAG.setRoot(Result.second); |
| 7069 | } |
| 7070 | |
| 7071 | if (EHPadBB) { |
| 7072 | // Insert a label at the end of the invoke call to mark the try range. This |
| 7073 | // can be used to detect deletion of the invoke via the MachineModuleInfo. |
| 7074 | MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); |
| 7075 | DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); |
| 7076 | |
| 7077 | // Inform MachineModuleInfo of range. |
| 7078 | auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); |
| 7079 | // There is a platform (e.g. wasm) that uses funclet style IR but does not |
| 7080 | // actually use outlined funclets and their LSDA info style. |
| 7081 | if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { |
| 7082 | assert(CLI.CS); |
| 7083 | WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); |
| 7084 | EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), |
| 7085 | BeginLabel, EndLabel); |
| 7086 | } else if (!isScopedEHPersonality(Pers)) { |
| 7087 | MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); |
| 7088 | } |
| 7089 | } |
| 7090 | |
| 7091 | return Result; |
| 7092 | } |
| 7093 | |
| 7094 | void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, |
| 7095 | bool isTailCall, |
| 7096 | const BasicBlock *EHPadBB) { |
| 7097 | auto &DL = DAG.getDataLayout(); |
| 7098 | FunctionType *FTy = CS.getFunctionType(); |
| 7099 | Type *RetTy = CS.getType(); |
| 7100 | |
| 7101 | TargetLowering::ArgListTy Args; |
| 7102 | Args.reserve(CS.arg_size()); |
| 7103 | |
| 7104 | const Value *SwiftErrorVal = nullptr; |
| 7105 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 7106 | |
| 7107 | // We can't tail call inside a function with a swifterror argument. Lowering |
| 7108 | // does not support this yet. It would have to move into the swifterror |
| 7109 | // register before the call. |
| 7110 | auto *Caller = CS.getInstruction()->getParent()->getParent(); |
| 7111 | if (TLI.supportSwiftError() && |
| 7112 | Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) |
| 7113 | isTailCall = false; |
| 7114 | |
| 7115 | for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); |
| 7116 | i != e; ++i) { |
| 7117 | TargetLowering::ArgListEntry Entry; |
| 7118 | const Value *V = *i; |
| 7119 | |
| 7120 | // Skip empty types |
| 7121 | if (V->getType()->isEmptyTy()) |
| 7122 | continue; |
| 7123 | |
| 7124 | SDValue ArgNode = getValue(V); |
| 7125 | Entry.Node = ArgNode; Entry.Ty = V->getType(); |
| 7126 | |
| 7127 | Entry.setAttributes(&CS, i - CS.arg_begin()); |
| 7128 | |
| 7129 | // Use swifterror virtual register as input to the call. |
| 7130 | if (Entry.IsSwiftError && TLI.supportSwiftError()) { |
| 7131 | SwiftErrorVal = V; |
| 7132 | // We find the virtual register for the actual swifterror argument. |
| 7133 | // Instead of using the Value, we use the virtual register instead. |
| 7134 | Entry.Node = DAG.getRegister( |
| 7135 | SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V), |
| 7136 | EVT(TLI.getPointerRangeTy(DL))); |
| 7137 | } |
| 7138 | |
| 7139 | Args.push_back(Entry); |
| 7140 | |
| 7141 | // If we have an explicit sret argument that is an Instruction, (i.e., it |
| 7142 | // might point to function-local memory), we can't meaningfully tail-call. |
| 7143 | if (Entry.IsSRet && isa<Instruction>(V)) |
| 7144 | isTailCall = false; |
| 7145 | } |
| 7146 | |
| 7147 | // Check if target-independent constraints permit a tail call here. |
| 7148 | // Target-dependent constraints are checked within TLI->LowerCallTo. |
| 7149 | if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) |
| 7150 | isTailCall = false; |
| 7151 | |
| 7152 | // Disable tail calls if there is an swifterror argument. Targets have not |
| 7153 | // been updated to support tail calls. |
| 7154 | if (TLI.supportSwiftError() && SwiftErrorVal) |
| 7155 | isTailCall = false; |
| 7156 | |
| 7157 | TargetLowering::CallLoweringInfo CLI(DAG); |
| 7158 | CLI.setDebugLoc(getCurSDLoc()) |
| 7159 | .setChain(getRoot()) |
| 7160 | .setCallee(RetTy, FTy, Callee, std::move(Args), CS) |
| 7161 | .setTailCall(isTailCall) |
| 7162 | .setConvergent(CS.isConvergent()); |
| 7163 | std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); |
| 7164 | |
| 7165 | if (Result.first.getNode()) { |
| 7166 | const Instruction *Inst = CS.getInstruction(); |
| 7167 | Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); |
| 7168 | setValue(Inst, Result.first); |
| 7169 | } |
| 7170 | |
| 7171 | // The last element of CLI.InVals has the SDValue for swifterror return. |
| 7172 | // Here we copy it to a virtual register and update SwiftErrorMap for |
| 7173 | // book-keeping. |
| 7174 | if (SwiftErrorVal && TLI.supportSwiftError()) { |
| 7175 | // Get the last element of InVals. |
| 7176 | SDValue Src = CLI.InVals.back(); |
| 7177 | unsigned VReg = SwiftError.getOrCreateVRegDefAt( |
| 7178 | CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal); |
| 7179 | SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); |
| 7180 | DAG.setRoot(CopyNode); |
| 7181 | } |
| 7182 | } |
| 7183 | |
| 7184 | static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, |
| 7185 | SelectionDAGBuilder &Builder) { |
| 7186 | unsigned AS = PtrVal->getType()->getPointerAddressSpace(); |
| 7187 | |
| 7188 | // Check to see if this load can be trivially constant folded, e.g. if the |
| 7189 | // input is from a string literal. |
| 7190 | if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { |
| 7191 | // Cast pointer to the type we really want to load. |
| 7192 | Type *LoadTy = |
| 7193 | Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); |
| 7194 | if (LoadVT.isVector()) |
| 7195 | LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); |
| 7196 | |
| 7197 | LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), |
| 7198 | PointerType::get(LoadTy, AS)); |
| 7199 | |
| 7200 | if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( |
| 7201 | const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) |
| 7202 | return Builder.getValue(LoadCst); |
| 7203 | } |
| 7204 | |
| 7205 | // Otherwise, we have to emit the load. If the pointer is to unfoldable but |
| 7206 | // still constant memory, the input chain can be the entry node. |
| 7207 | SDValue Root; |
| 7208 | bool ConstantMemory = false; |
| 7209 | |
| 7210 | // Do not serialize (non-volatile) loads of constant memory with anything. |
| 7211 | if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { |
| 7212 | Root = Builder.DAG.getEntryNode(); |
| 7213 | ConstantMemory = true; |
| 7214 | } else { |
| 7215 | // Do not serialize non-volatile loads against each other. |
| 7216 | Root = Builder.DAG.getRoot(); |
| 7217 | } |
| 7218 | |
| 7219 | SDValue Ptr = Builder.getValue(PtrVal); |
| 7220 | SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, |
| 7221 | Ptr, MachinePointerInfo(PtrVal), |
| 7222 | /* Alignment = */ 1); |
| 7223 | |
| 7224 | if (!ConstantMemory) |
| 7225 | Builder.PendingLoads.push_back(LoadVal.getValue(1)); |
| 7226 | return LoadVal; |
| 7227 | } |
| 7228 | |
| 7229 | /// Record the value for an instruction that produces an integer result, |
| 7230 | /// converting the type where necessary. |
| 7231 | void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, |
| 7232 | SDValue Value, |
| 7233 | bool IsSigned) { |
| 7234 | EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 7235 | I.getType(), true); |
| 7236 | if (IsSigned) |
| 7237 | Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); |
| 7238 | else |
| 7239 | Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); |
| 7240 | setValue(&I, Value); |
| 7241 | } |
| 7242 | |
| 7243 | /// See if we can lower a memcmp call into an optimized form. If so, return |
| 7244 | /// true and lower it. Otherwise return false, and it will be lowered like a |
| 7245 | /// normal call. |
| 7246 | /// The caller already checked that \p I calls the appropriate LibFunc with a |
| 7247 | /// correct prototype. |
| 7248 | bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { |
| 7249 | const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); |
| 7250 | const Value *Size = I.getArgOperand(2); |
| 7251 | const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); |
| 7252 | if (CSize && CSize->getZExtValue() == 0) { |
| 7253 | EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), |
| 7254 | I.getType(), true); |
| 7255 | setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); |
| 7256 | return true; |
| 7257 | } |
| 7258 | |
| 7259 | const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); |
| 7260 | std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( |
| 7261 | DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), |
| 7262 | getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); |
| 7263 | if (Res.first.getNode()) { |
| 7264 | processIntegerCallValue(I, Res.first, true); |
| 7265 | PendingLoads.push_back(Res.second); |
| 7266 | return true; |
| 7267 | } |
| 7268 | |
| 7269 | // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 |
| 7270 | // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 |
| 7271 | if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) |
| 7272 | return false; |
| 7273 | |
| 7274 | // If the target has a fast compare for the given size, it will return a |
| 7275 | // preferred load type for that size. Require that the load VT is legal and |
| 7276 | // that the target supports unaligned loads of that type. Otherwise, return |
| 7277 | // INVALID. |
| 7278 | auto hasFastLoadsAndCompare = [&](unsigned NumBits) { |
| 7279 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 7280 | MVT LVT = TLI.hasFastEqualityCompare(NumBits); |
| 7281 | if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { |
| 7282 | // TODO: Handle 5 byte compare as 4-byte + 1 byte. |
| 7283 | // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. |
| 7284 | // TODO: Check alignment of src and dest ptrs. |
| 7285 | unsigned DstAS = LHS->getType()->getPointerAddressSpace(); |
| 7286 | unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); |
| 7287 | if (!TLI.isTypeLegal(LVT) || |
| 7288 | !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || |
| 7289 | !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) |
| 7290 | LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; |
| 7291 | } |
| 7292 | |
| 7293 | return LVT; |
| 7294 | }; |
| 7295 | |
| 7296 | // This turns into unaligned loads. We only do this if the target natively |
| 7297 | // supports the MVT we'll be loading or if it is small enough (<= 4) that |
| 7298 | // we'll only produce a small number of byte loads. |
| 7299 | MVT LoadVT; |
| 7300 | unsigned NumBitsToCompare = CSize->getZExtValue() * 8; |
| 7301 | switch (NumBitsToCompare) { |
| 7302 | default: |
| 7303 | return false; |
| 7304 | case 16: |
| 7305 | LoadVT = MVT::i16; |
| 7306 | break; |
| 7307 | case 32: |
| 7308 | LoadVT = MVT::i32; |
| 7309 | break; |
| 7310 | case 64: |
| 7311 | case 128: |
| 7312 | case 256: |
| 7313 | LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); |
| 7314 | break; |
| 7315 | } |
| 7316 | |
| 7317 | if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) |
| 7318 | return false; |
| 7319 | |
| 7320 | SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); |
| 7321 | SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); |
| 7322 | |
| 7323 | // Bitcast to a wide integer type if the loads are vectors. |
| 7324 | if (LoadVT.isVector()) { |
| 7325 | EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); |
| 7326 | LoadL = DAG.getBitcast(CmpVT, LoadL); |
| 7327 | LoadR = DAG.getBitcast(CmpVT, LoadR); |
| 7328 | } |
| 7329 | |
| 7330 | SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); |
| 7331 | processIntegerCallValue(I, Cmp, false); |
| 7332 | return true; |
| 7333 | } |
| 7334 | |
| 7335 | /// See if we can lower a memchr call into an optimized form. If so, return |
| 7336 | /// true and lower it. Otherwise return false, and it will be lowered like a |
| 7337 | /// normal call. |
| 7338 | /// The caller already checked that \p I calls the appropriate LibFunc with a |
| 7339 | /// correct prototype. |
| 7340 | bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { |
| 7341 | const Value *Src = I.getArgOperand(0); |
| 7342 | const Value *Char = I.getArgOperand(1); |
| 7343 | const Value *Length = I.getArgOperand(2); |
| 7344 | |
| 7345 | const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); |
| 7346 | std::pair<SDValue, SDValue> Res = |
| 7347 | TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), |
| 7348 | getValue(Src), getValue(Char), getValue(Length), |
| 7349 | MachinePointerInfo(Src)); |
| 7350 | if (Res.first.getNode()) { |
| 7351 | setValue(&I, Res.first); |
| 7352 | PendingLoads.push_back(Res.second); |
| 7353 | return true; |
| 7354 | } |
| 7355 | |
| 7356 | return false; |
| 7357 | } |
| 7358 | |
| 7359 | /// See if we can lower a mempcpy call into an optimized form. If so, return |
| 7360 | /// true and lower it. Otherwise return false, and it will be lowered like a |
| 7361 | /// normal call. |
| 7362 | /// The caller already checked that \p I calls the appropriate LibFunc with a |
| 7363 | /// correct prototype. |
| 7364 | bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { |
| 7365 | SDValue Dst = getValue(I.getArgOperand(0)); |
| 7366 | SDValue Src = getValue(I.getArgOperand(1)); |
| 7367 | SDValue Size = getValue(I.getArgOperand(2)); |
| 7368 | |
| 7369 | unsigned DstAlign = DAG.InferPtrAlignment(Dst); |
| 7370 | unsigned SrcAlign = DAG.InferPtrAlignment(Src); |
| 7371 | unsigned Align = std::min(DstAlign, SrcAlign); |
| 7372 | if (Align == 0) // Alignment of one or both could not be inferred. |
| 7373 | Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. |
| 7374 | |
| 7375 | bool isVol = false; |
| 7376 | SDLoc sdl = getCurSDLoc(); |
| 7377 | |
| 7378 | const bool MustPreserveCheriTags = I.hasFnAttr("must-preserve-cheri-tags" ); |
| 7379 | Attribute CopyType = |
| 7380 | I.getAttribute(AttributeList::FunctionIndex, "frontend-memtransfer-type" ); |
| 7381 | // In the mempcpy context we need to pass in a false value for isTailCall |
| 7382 | // because the return pointer needs to be adjusted by the size of |
| 7383 | // the copied memory. |
| 7384 | SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, |
| 7385 | false, /*isTailCall=*/false, MustPreserveCheriTags, |
| 7386 | MachinePointerInfo(I.getArgOperand(0)), |
| 7387 | MachinePointerInfo(I.getArgOperand(1)), |
| 7388 | CopyType.getValueAsString()); |
| 7389 | assert(MC.getNode() != nullptr && |
| 7390 | "** memcpy should not be lowered as TailCall in mempcpy context **" ); |
| 7391 | DAG.setRoot(MC); |
| 7392 | |
| 7393 | // Check if Size needs to be truncated or extended. |
| 7394 | Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); |
| 7395 | |
| 7396 | // Adjust return pointer to point just past the last dst byte. |
| 7397 | SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), |
| 7398 | Dst, Size); |
| 7399 | setValue(&I, DstPlusSize); |
| 7400 | return true; |
| 7401 | } |
| 7402 | |
| 7403 | /// See if we can lower a strcpy call into an optimized form. If so, return |
| 7404 | /// true and lower it, otherwise return false and it will be lowered like a |
| 7405 | /// normal call. |
| 7406 | /// The caller already checked that \p I calls the appropriate LibFunc with a |
| 7407 | /// correct prototype. |
| 7408 | bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { |
| 7409 | const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); |
| 7410 | |
| 7411 | const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); |
| 7412 | std::pair<SDValue, SDValue> Res = |
| 7413 | TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), |
| 7414 | getValue(Arg0), getValue(Arg1), |
| 7415 | MachinePointerInfo(Arg0), |
| 7416 | MachinePointerInfo(Arg1), isStpcpy); |
| 7417 | if (Res.first.getNode()) { |
| 7418 | setValue(&I, Res.first); |
| 7419 | DAG.setRoot(Res.second); |
| 7420 | return true; |
| 7421 | } |
| 7422 | |
| 7423 | return false; |
| 7424 | } |
| 7425 | |
| 7426 | /// See if we can lower a strcmp call into an optimized form. If so, return |
| 7427 | /// true and lower it, otherwise return false and it will be lowered like a |
| 7428 | /// normal call. |
| 7429 | /// The caller already checked that \p I calls the appropriate LibFunc with a |
| 7430 | /// correct prototype. |
| 7431 | bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { |
| 7432 | const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); |
| 7433 | |
| 7434 | const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); |
| 7435 | std::pair<SDValue, SDValue> Res = |
| 7436 | TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), |
| 7437 | getValue(Arg0), getValue(Arg1), |
| 7438 | MachinePointerInfo(Arg0), |
| 7439 | MachinePointerInfo(Arg1)); |
| 7440 | if (Res.first.getNode()) { |
| 7441 | processIntegerCallValue(I, Res.first, true); |
| 7442 | PendingLoads.push_back(Res.second); |
| 7443 | return true; |
| 7444 | } |
| 7445 | |
| 7446 | return false; |
| 7447 | } |
| 7448 | |
| 7449 | /// See if we can lower a strlen call into an optimized form. If so, return |
| 7450 | /// true and lower it, otherwise return false and it will be lowered like a |
| 7451 | /// normal call. |
| 7452 | /// The caller already checked that \p I calls the appropriate LibFunc with a |
| 7453 | /// correct prototype. |
| 7454 | bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { |
| 7455 | const Value *Arg0 = I.getArgOperand(0); |
| 7456 | |
| 7457 | const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); |
| 7458 | std::pair<SDValue, SDValue> Res = |
| 7459 | TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), |
| 7460 | getValue(Arg0), MachinePointerInfo(Arg0)); |
| 7461 | if (Res.first.getNode()) { |
| 7462 | processIntegerCallValue(I, Res.first, false); |
| 7463 | PendingLoads.push_back(Res.second); |
| 7464 | return true; |
| 7465 | } |
| 7466 | |
| 7467 | return false; |
| 7468 | } |
| 7469 | |
| 7470 | /// See if we can lower a strnlen call into an optimized form. If so, return |
| 7471 | /// true and lower it, otherwise return false and it will be lowered like a |
| 7472 | /// normal call. |
| 7473 | /// The caller already checked that \p I calls the appropriate LibFunc with a |
| 7474 | /// correct prototype. |
| 7475 | bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { |
| 7476 | const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); |
| 7477 | |
| 7478 | const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); |
| 7479 | std::pair<SDValue, SDValue> Res = |
| 7480 | TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), |
| 7481 | getValue(Arg0), getValue(Arg1), |
| 7482 | MachinePointerInfo(Arg0)); |
| 7483 | if (Res.first.getNode()) { |
| 7484 | processIntegerCallValue(I, Res.first, false); |
| 7485 | PendingLoads.push_back(Res.second); |
| 7486 | return true; |
| 7487 | } |
| 7488 | |
| 7489 | return false; |
| 7490 | } |
| 7491 | |
| 7492 | /// See if we can lower a unary floating-point operation into an SDNode with |
| 7493 | /// the specified Opcode. If so, return true and lower it, otherwise return |
| 7494 | /// false and it will be lowered like a normal call. |
| 7495 | /// The caller already checked that \p I calls the appropriate LibFunc with a |
| 7496 | /// correct prototype. |
| 7497 | bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, |
| 7498 | unsigned Opcode) { |
| 7499 | // We already checked this call's prototype; verify it doesn't modify errno. |
| 7500 | if (!I.onlyReadsMemory()) |
| 7501 | return false; |
| 7502 | |
| 7503 | SDValue Tmp = getValue(I.getArgOperand(0)); |
| 7504 | setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); |
| 7505 | return true; |
| 7506 | } |
| 7507 | |
| 7508 | /// See if we can lower a binary floating-point operation into an SDNode with |
| 7509 | /// the specified Opcode. If so, return true and lower it. Otherwise return |
| 7510 | /// false, and it will be lowered like a normal call. |
| 7511 | /// The caller already checked that \p I calls the appropriate LibFunc with a |
| 7512 | /// correct prototype. |
| 7513 | bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, |
| 7514 | unsigned Opcode) { |
| 7515 | // We already checked this call's prototype; verify it doesn't modify errno. |
| 7516 | if (!I.onlyReadsMemory()) |
| 7517 | return false; |
| 7518 | |
| 7519 | SDValue Tmp0 = getValue(I.getArgOperand(0)); |
| 7520 | SDValue Tmp1 = getValue(I.getArgOperand(1)); |
| 7521 | EVT VT = Tmp0.getValueType(); |
| 7522 | setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); |
| 7523 | return true; |
| 7524 | } |
| 7525 | |
| 7526 | void SelectionDAGBuilder::visitCall(const CallInst &I) { |
| 7527 | // Handle inline assembly differently. |
| 7528 | if (isa<InlineAsm>(I.getCalledValue())) { |
| 7529 | visitInlineAsm(&I); |
| 7530 | return; |
| 7531 | } |
| 7532 | |
| 7533 | if (Function *F = I.getCalledFunction()) { |
| 7534 | if (F->isDeclaration()) { |
| 7535 | // Is this an LLVM intrinsic or a target-specific intrinsic? |
| 7536 | unsigned IID = F->getIntrinsicID(); |
| 7537 | if (!IID) |
| 7538 | if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) |
| 7539 | IID = II->getIntrinsicID(F); |
| 7540 | |
| 7541 | if (IID) { |
| 7542 | visitIntrinsicCall(I, IID); |
| 7543 | return; |
| 7544 | } |
| 7545 | } |
| 7546 | |
| 7547 | // Check for well-known libc/libm calls. If the function is internal, it |
| 7548 | // can't be a library call. Don't do the check if marked as nobuiltin for |
| 7549 | // some reason or the call site requires strict floating point semantics. |
| 7550 | LibFunc Func; |
| 7551 | if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && |
| 7552 | F->hasName() && LibInfo->getLibFunc(*F, Func) && |
| 7553 | LibInfo->hasOptimizedCodeGen(Func)) { |
| 7554 | switch (Func) { |
| 7555 | default: break; |
| 7556 | case LibFunc_copysign: |
| 7557 | case LibFunc_copysignf: |
| 7558 | case LibFunc_copysignl: |
| 7559 | // We already checked this call's prototype; verify it doesn't modify |
| 7560 | // errno. |
| 7561 | if (I.onlyReadsMemory()) { |
| 7562 | SDValue LHS = getValue(I.getArgOperand(0)); |
| 7563 | SDValue RHS = getValue(I.getArgOperand(1)); |
| 7564 | setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), |
| 7565 | LHS.getValueType(), LHS, RHS)); |
| 7566 | return; |
| 7567 | } |
| 7568 | break; |
| 7569 | case LibFunc_fabs: |
| 7570 | case LibFunc_fabsf: |
| 7571 | case LibFunc_fabsl: |
| 7572 | if (visitUnaryFloatCall(I, ISD::FABS)) |
| 7573 | return; |
| 7574 | break; |
| 7575 | case LibFunc_fmin: |
| 7576 | case LibFunc_fminf: |
| 7577 | case LibFunc_fminl: |
| 7578 | if (visitBinaryFloatCall(I, ISD::FMINNUM)) |
| 7579 | return; |
| 7580 | break; |
| 7581 | case LibFunc_fmax: |
| 7582 | case LibFunc_fmaxf: |
| 7583 | case LibFunc_fmaxl: |
| 7584 | if (visitBinaryFloatCall(I, ISD::FMAXNUM)) |
| 7585 | return; |
| 7586 | break; |
| 7587 | case LibFunc_sin: |
| 7588 | case LibFunc_sinf: |
| 7589 | case LibFunc_sinl: |
| 7590 | if (visitUnaryFloatCall(I, ISD::FSIN)) |
| 7591 | return; |
| 7592 | break; |
| 7593 | case LibFunc_cos: |
| 7594 | case LibFunc_cosf: |
| 7595 | case LibFunc_cosl: |
| 7596 | if (visitUnaryFloatCall(I, ISD::FCOS)) |
| 7597 | return; |
| 7598 | break; |
| 7599 | case LibFunc_sqrt: |
| 7600 | case LibFunc_sqrtf: |
| 7601 | case LibFunc_sqrtl: |
| 7602 | case LibFunc_sqrt_finite: |
| 7603 | case LibFunc_sqrtf_finite: |
| 7604 | case LibFunc_sqrtl_finite: |
| 7605 | if (visitUnaryFloatCall(I, ISD::FSQRT)) |
| 7606 | return; |
| 7607 | break; |
| 7608 | case LibFunc_floor: |
| 7609 | case LibFunc_floorf: |
| 7610 | case LibFunc_floorl: |
| 7611 | if (visitUnaryFloatCall(I, ISD::FFLOOR)) |
| 7612 | return; |
| 7613 | break; |
| 7614 | case LibFunc_nearbyint: |
| 7615 | case LibFunc_nearbyintf: |
| 7616 | case LibFunc_nearbyintl: |
| 7617 | if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) |
| 7618 | return; |
| 7619 | break; |
| 7620 | case LibFunc_ceil: |
| 7621 | case LibFunc_ceilf: |
| 7622 | case LibFunc_ceill: |
| 7623 | if (visitUnaryFloatCall(I, ISD::FCEIL)) |
| 7624 | return; |
| 7625 | break; |
| 7626 | case LibFunc_rint: |
| 7627 | case LibFunc_rintf: |
| 7628 | case LibFunc_rintl: |
| 7629 | if (visitUnaryFloatCall(I, ISD::FRINT)) |
| 7630 | return; |
| 7631 | break; |
| 7632 | case LibFunc_round: |
| 7633 | case LibFunc_roundf: |
| 7634 | case LibFunc_roundl: |
| 7635 | if (visitUnaryFloatCall(I, ISD::FROUND)) |
| 7636 | return; |
| 7637 | break; |
| 7638 | case LibFunc_trunc: |
| 7639 | case LibFunc_truncf: |
| 7640 | case LibFunc_truncl: |
| 7641 | if (visitUnaryFloatCall(I, ISD::FTRUNC)) |
| 7642 | return; |
| 7643 | break; |
| 7644 | case LibFunc_log2: |
| 7645 | case LibFunc_log2f: |
| 7646 | case LibFunc_log2l: |
| 7647 | if (visitUnaryFloatCall(I, ISD::FLOG2)) |
| 7648 | return; |
| 7649 | break; |
| 7650 | case LibFunc_exp2: |
| 7651 | case LibFunc_exp2f: |
| 7652 | case LibFunc_exp2l: |
| 7653 | if (visitUnaryFloatCall(I, ISD::FEXP2)) |
| 7654 | return; |
| 7655 | break; |
| 7656 | case LibFunc_memcmp: |
| 7657 | if (visitMemCmpCall(I)) |
| 7658 | return; |
| 7659 | break; |
| 7660 | case LibFunc_mempcpy: |
| 7661 | if (visitMemPCpyCall(I)) |
| 7662 | return; |
| 7663 | break; |
| 7664 | case LibFunc_memchr: |
| 7665 | if (visitMemChrCall(I)) |
| 7666 | return; |
| 7667 | break; |
| 7668 | case LibFunc_strcpy: |
| 7669 | if (visitStrCpyCall(I, false)) |
| 7670 | return; |
| 7671 | break; |
| 7672 | case LibFunc_stpcpy: |
| 7673 | if (visitStrCpyCall(I, true)) |
| 7674 | return; |
| 7675 | break; |
| 7676 | case LibFunc_strcmp: |
| 7677 | if (visitStrCmpCall(I)) |
| 7678 | return; |
| 7679 | break; |
| 7680 | case LibFunc_strlen: |
| 7681 | if (visitStrLenCall(I)) |
| 7682 | return; |
| 7683 | break; |
| 7684 | case LibFunc_strnlen: |
| 7685 | if (visitStrNLenCall(I)) |
| 7686 | return; |
| 7687 | break; |
| 7688 | } |
| 7689 | } |
| 7690 | } |
| 7691 | |
| 7692 | // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't |
| 7693 | // have to do anything here to lower funclet bundles. |
| 7694 | assert(!I.hasOperandBundlesOtherThan( |
| 7695 | {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && |
| 7696 | "Cannot lower calls with arbitrary operand bundles!" ); |
| 7697 | |
| 7698 | SDValue Callee = getValue(I.getCalledValue()); |
| 7699 | |
| 7700 | if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) |
| 7701 | LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); |
| 7702 | else |
| 7703 | // Check if we can potentially perform a tail call. More detailed checking |
| 7704 | // is be done within LowerCallTo, after more information about the call is |
| 7705 | // known. |
| 7706 | LowerCallTo(&I, Callee, I.isTailCall()); |
| 7707 | } |
| 7708 | |
| 7709 | namespace { |
| 7710 | |
| 7711 | /// AsmOperandInfo - This contains information for each constraint that we are |
| 7712 | /// lowering. |
| 7713 | class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { |
| 7714 | public: |
| 7715 | /// CallOperand - If this is the result output operand or a clobber |
| 7716 | /// this is null, otherwise it is the incoming operand to the CallInst. |
| 7717 | /// This gets modified as the asm is processed. |
| 7718 | SDValue CallOperand; |
| 7719 | |
| 7720 | /// AssignedRegs - If this is a register or register class operand, this |
| 7721 | /// contains the set of register corresponding to the operand. |
| 7722 | RegsForValue AssignedRegs; |
| 7723 | |
| 7724 | explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) |
| 7725 | : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { |
| 7726 | } |
| 7727 | |
| 7728 | /// Whether or not this operand accesses memory |
| 7729 | bool hasMemory(const TargetLowering &TLI) const { |
| 7730 | // Indirect operand accesses access memory. |
| 7731 | if (isIndirect) |
| 7732 | return true; |
| 7733 | |
| 7734 | for (const auto &Code : Codes) |
| 7735 | if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) |
| 7736 | return true; |
| 7737 | |
| 7738 | return false; |
| 7739 | } |
| 7740 | |
| 7741 | /// getCallOperandValEVT - Return the EVT of the Value* that this operand |
| 7742 | /// corresponds to. If there is no Value* for this operand, it returns |
| 7743 | /// MVT::Other. |
| 7744 | EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, |
| 7745 | const DataLayout &DL) const { |
| 7746 | if (!CallOperandVal) return MVT::Other; |
| 7747 | |
| 7748 | if (isa<BasicBlock>(CallOperandVal)) |
| 7749 | return TLI.getPointerTy(DL, DL.getProgramAddressSpace()); |
| 7750 | |
| 7751 | llvm::Type *OpTy = CallOperandVal->getType(); |
| 7752 | |
| 7753 | // FIXME: code duplicated from TargetLowering::ParseConstraints(). |
| 7754 | // If this is an indirect operand, the operand is a pointer to the |
| 7755 | // accessed type. |
| 7756 | if (isIndirect) { |
| 7757 | PointerType *PtrTy = dyn_cast<PointerType>(OpTy); |
| 7758 | if (!PtrTy) |
| 7759 | report_fatal_error("Indirect operand for inline asm not a pointer!" ); |
| 7760 | OpTy = PtrTy->getElementType(); |
| 7761 | } |
| 7762 | |
| 7763 | // Look for vector wrapped in a struct. e.g. { <16 x i8> }. |
| 7764 | if (StructType *STy = dyn_cast<StructType>(OpTy)) |
| 7765 | if (STy->getNumElements() == 1) |
| 7766 | OpTy = STy->getElementType(0); |
| 7767 | |
| 7768 | // If OpTy is not a single value, it may be a struct/union that we |
| 7769 | // can tile with integers. |
| 7770 | if (!OpTy->isSingleValueType() && OpTy->isSized()) { |
| 7771 | unsigned BitSize = DL.getTypeSizeInBits(OpTy); |
| 7772 | switch (BitSize) { |
| 7773 | default: break; |
| 7774 | case 1: |
| 7775 | case 8: |
| 7776 | case 16: |
| 7777 | case 32: |
| 7778 | case 64: |
| 7779 | case 128: |
| 7780 | OpTy = IntegerType::get(Context, BitSize); |
| 7781 | break; |
| 7782 | } |
| 7783 | } |
| 7784 | |
| 7785 | return TLI.getValueType(DL, OpTy, true); |
| 7786 | } |
| 7787 | }; |
| 7788 | |
| 7789 | using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; |
| 7790 | |
| 7791 | } // end anonymous namespace |
| 7792 | |
| 7793 | /// Make sure that the output operand \p OpInfo and its corresponding input |
| 7794 | /// operand \p MatchingOpInfo have compatible constraint types (otherwise error |
| 7795 | /// out). |
| 7796 | static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, |
| 7797 | SDISelAsmOperandInfo &MatchingOpInfo, |
| 7798 | SelectionDAG &DAG) { |
| 7799 | if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) |
| 7800 | return; |
| 7801 | |
| 7802 | const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); |
| 7803 | const auto &TLI = DAG.getTargetLoweringInfo(); |
| 7804 | |
| 7805 | std::pair<unsigned, const TargetRegisterClass *> MatchRC = |
| 7806 | TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, |
| 7807 | OpInfo.ConstraintVT); |
| 7808 | std::pair<unsigned, const TargetRegisterClass *> InputRC = |
| 7809 | TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, |
| 7810 | MatchingOpInfo.ConstraintVT); |
| 7811 | if ((OpInfo.ConstraintVT.isInteger() != |
| 7812 | MatchingOpInfo.ConstraintVT.isInteger()) || |
| 7813 | (MatchRC.second != InputRC.second)) { |
| 7814 | // FIXME: error out in a more elegant fashion |
| 7815 | report_fatal_error("Unsupported asm: input constraint" |
| 7816 | " with a matching output constraint of" |
| 7817 | " incompatible type!" ); |
| 7818 | } |
| 7819 | MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; |
| 7820 | } |
| 7821 | |
| 7822 | /// Get a direct memory input to behave well as an indirect operand. |
| 7823 | /// This may introduce stores, hence the need for a \p Chain. |
| 7824 | /// \return The (possibly updated) chain. |
| 7825 | static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, |
| 7826 | SDISelAsmOperandInfo &OpInfo, |
| 7827 | SelectionDAG &DAG) { |
| 7828 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 7829 | |
| 7830 | // If we don't have an indirect input, put it in the constpool if we can, |
| 7831 | // otherwise spill it to a stack slot. |
| 7832 | // TODO: This isn't quite right. We need to handle these according to |
| 7833 | // the addressing mode that the constraint wants. Also, this may take |
| 7834 | // an additional register for the computation and we don't want that |
| 7835 | // either. |
| 7836 | |
| 7837 | // If the operand is a float, integer, or vector constant, spill to a |
| 7838 | // constant pool entry to get its address. |
| 7839 | const Value *OpVal = OpInfo.CallOperandVal; |
| 7840 | if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || |
| 7841 | isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { |
| 7842 | OpInfo.CallOperand = DAG.getConstantPool( |
| 7843 | cast<Constant>(OpVal), |
| 7844 | TLI.getPointerTy(DAG.getDataLayout(), |
| 7845 | DAG.getDataLayout().getGlobalsAddressSpace())); |
| 7846 | return Chain; |
| 7847 | } |
| 7848 | |
| 7849 | // Otherwise, create a stack slot and emit a store to it before the asm. |
| 7850 | Type *Ty = OpVal->getType(); |
| 7851 | auto &DL = DAG.getDataLayout(); |
| 7852 | uint64_t TySize = DL.getTypeAllocSize(Ty); |
| 7853 | unsigned Align = DL.getPrefTypeAlignment(Ty); |
| 7854 | MachineFunction &MF = DAG.getMachineFunction(); |
| 7855 | int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); |
| 7856 | SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); |
| 7857 | Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, |
| 7858 | MachinePointerInfo::getFixedStack(MF, SSFI), |
| 7859 | TLI.getMemValueType(DL, Ty)); |
| 7860 | OpInfo.CallOperand = StackSlot; |
| 7861 | |
| 7862 | return Chain; |
| 7863 | } |
| 7864 | |
| 7865 | /// GetRegistersForValue - Assign registers (virtual or physical) for the |
| 7866 | /// specified operand. We prefer to assign virtual registers, to allow the |
| 7867 | /// register allocator to handle the assignment process. However, if the asm |
| 7868 | /// uses features that we can't model on machineinstrs, we have SDISel do the |
| 7869 | /// allocation. This produces generally horrible, but correct, code. |
| 7870 | /// |
| 7871 | /// OpInfo describes the operand |
| 7872 | /// RefOpInfo describes the matching operand if any, the operand otherwise |
| 7873 | static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, |
| 7874 | SDISelAsmOperandInfo &OpInfo, |
| 7875 | SDISelAsmOperandInfo &RefOpInfo) { |
| 7876 | LLVMContext &Context = *DAG.getContext(); |
| 7877 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 7878 | |
| 7879 | MachineFunction &MF = DAG.getMachineFunction(); |
| 7880 | SmallVector<unsigned, 4> Regs; |
| 7881 | const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); |
| 7882 | |
| 7883 | // No work to do for memory operations. |
| 7884 | if (OpInfo.ConstraintType == TargetLowering::C_Memory) |
| 7885 | return; |
| 7886 | |
| 7887 | // If this is a constraint for a single physreg, or a constraint for a |
| 7888 | // register class, find it. |
| 7889 | unsigned AssignedReg; |
| 7890 | const TargetRegisterClass *RC; |
| 7891 | std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( |
| 7892 | &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); |
| 7893 | // RC is unset only on failure. Return immediately. |
| 7894 | if (!RC) |
| 7895 | return; |
| 7896 | |
| 7897 | // Get the actual register value type. This is important, because the user |
| 7898 | // may have asked for (e.g.) the AX register in i32 type. We need to |
| 7899 | // remember that AX is actually i16 to get the right extension. |
| 7900 | const MVT RegVT = *TRI.legalclasstypes_begin(*RC); |
| 7901 | |
| 7902 | if (OpInfo.ConstraintVT != MVT::Other) { |
| 7903 | // If this is an FP operand in an integer register (or visa versa), or more |
| 7904 | // generally if the operand value disagrees with the register class we plan |
| 7905 | // to stick it in, fix the operand type. |
| 7906 | // |
| 7907 | // If this is an input value, the bitcast to the new type is done now. |
| 7908 | // Bitcast for output value is done at the end of visitInlineAsm(). |
| 7909 | if ((OpInfo.Type == InlineAsm::isOutput || |
| 7910 | OpInfo.Type == InlineAsm::isInput) && |
| 7911 | !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { |
| 7912 | // Try to convert to the first EVT that the reg class contains. If the |
| 7913 | // types are identical size, use a bitcast to convert (e.g. two differing |
| 7914 | // vector types). Note: output bitcast is done at the end of |
| 7915 | // visitInlineAsm(). |
| 7916 | if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { |
| 7917 | // Exclude indirect inputs while they are unsupported because the code |
| 7918 | // to perform the load is missing and thus OpInfo.CallOperand still |
| 7919 | // refers to the input address rather than the pointed-to value. |
| 7920 | if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) |
| 7921 | OpInfo.CallOperand = |
| 7922 | DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); |
| 7923 | OpInfo.ConstraintVT = RegVT; |
| 7924 | // If the operand is an FP value and we want it in integer registers, |
| 7925 | // use the corresponding integer type. This turns an f64 value into |
| 7926 | // i64, which can be passed with two i32 values on a 32-bit machine. |
| 7927 | } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { |
| 7928 | MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); |
| 7929 | if (OpInfo.Type == InlineAsm::isInput) |
| 7930 | OpInfo.CallOperand = |
| 7931 | DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); |
| 7932 | OpInfo.ConstraintVT = VT; |
| 7933 | } |
| 7934 | } |
| 7935 | } |
| 7936 | |
| 7937 | // No need to allocate a matching input constraint since the constraint it's |
| 7938 | // matching to has already been allocated. |
| 7939 | if (OpInfo.isMatchingInputConstraint()) |
| 7940 | return; |
| 7941 | |
| 7942 | EVT ValueVT = OpInfo.ConstraintVT; |
| 7943 | if (OpInfo.ConstraintVT == MVT::Other) |
| 7944 | ValueVT = RegVT; |
| 7945 | |
| 7946 | // Initialize NumRegs. |
| 7947 | unsigned NumRegs = 1; |
| 7948 | if (OpInfo.ConstraintVT != MVT::Other) |
| 7949 | NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); |
| 7950 | |
| 7951 | // If this is a constraint for a specific physical register, like {r17}, |
| 7952 | // assign it now. |
| 7953 | |
| 7954 | // If this associated to a specific register, initialize iterator to correct |
| 7955 | // place. If virtual, make sure we have enough registers |
| 7956 | |
| 7957 | // Initialize iterator if necessary |
| 7958 | TargetRegisterClass::iterator I = RC->begin(); |
| 7959 | MachineRegisterInfo &RegInfo = MF.getRegInfo(); |
| 7960 | |
| 7961 | // Do not check for single registers. |
| 7962 | if (AssignedReg) { |
| 7963 | for (; *I != AssignedReg; ++I) |
| 7964 | assert(I != RC->end() && "AssignedReg should be member of RC" ); |
| 7965 | } |
| 7966 | |
| 7967 | for (; NumRegs; --NumRegs, ++I) { |
| 7968 | assert(I != RC->end() && "Ran out of registers to allocate!" ); |
| 7969 | auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC); |
| 7970 | Regs.push_back(R); |
| 7971 | } |
| 7972 | |
| 7973 | OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); |
| 7974 | } |
| 7975 | |
| 7976 | static unsigned |
| 7977 | findMatchingInlineAsmOperand(unsigned OperandNo, |
| 7978 | const std::vector<SDValue> &AsmNodeOperands) { |
| 7979 | // Scan until we find the definition we already emitted of this operand. |
| 7980 | unsigned CurOp = InlineAsm::Op_FirstOperand; |
| 7981 | for (; OperandNo; --OperandNo) { |
| 7982 | // Advance to the next operand. |
| 7983 | unsigned OpFlag = |
| 7984 | cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); |
| 7985 | assert((InlineAsm::isRegDefKind(OpFlag) || |
| 7986 | InlineAsm::isRegDefEarlyClobberKind(OpFlag) || |
| 7987 | InlineAsm::isMemKind(OpFlag)) && |
| 7988 | "Skipped past definitions?" ); |
| 7989 | CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; |
| 7990 | } |
| 7991 | return CurOp; |
| 7992 | } |
| 7993 | |
| 7994 | namespace { |
| 7995 | |
| 7996 | class { |
| 7997 | unsigned = 0; |
| 7998 | |
| 7999 | public: |
| 8000 | explicit (ImmutableCallSite CS) { |
| 8001 | const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); |
| 8002 | if (IA->hasSideEffects()) |
| 8003 | Flags |= InlineAsm::Extra_HasSideEffects; |
| 8004 | if (IA->isAlignStack()) |
| 8005 | Flags |= InlineAsm::Extra_IsAlignStack; |
| 8006 | if (CS.isConvergent()) |
| 8007 | Flags |= InlineAsm::Extra_IsConvergent; |
| 8008 | Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; |
| 8009 | } |
| 8010 | |
| 8011 | void update(const TargetLowering::AsmOperandInfo &OpInfo) { |
| 8012 | // Ideally, we would only check against memory constraints. However, the |
| 8013 | // meaning of an Other constraint can be target-specific and we can't easily |
| 8014 | // reason about it. Therefore, be conservative and set MayLoad/MayStore |
| 8015 | // for Other constraints as well. |
| 8016 | if (OpInfo.ConstraintType == TargetLowering::C_Memory || |
| 8017 | OpInfo.ConstraintType == TargetLowering::C_Other) { |
| 8018 | if (OpInfo.Type == InlineAsm::isInput) |
| 8019 | Flags |= InlineAsm::Extra_MayLoad; |
| 8020 | else if (OpInfo.Type == InlineAsm::isOutput) |
| 8021 | Flags |= InlineAsm::Extra_MayStore; |
| 8022 | else if (OpInfo.Type == InlineAsm::isClobber) |
| 8023 | Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); |
| 8024 | } |
| 8025 | } |
| 8026 | |
| 8027 | unsigned () const { return Flags; } |
| 8028 | }; |
| 8029 | |
| 8030 | } // end anonymous namespace |
| 8031 | |
| 8032 | /// visitInlineAsm - Handle a call to an InlineAsm object. |
| 8033 | void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { |
| 8034 | const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); |
| 8035 | |
| 8036 | /// ConstraintOperands - Information about all of the constraints. |
| 8037 | SDISelAsmOperandInfoVector ConstraintOperands; |
| 8038 | |
| 8039 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 8040 | TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( |
| 8041 | DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); |
| 8042 | |
| 8043 | // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, |
| 8044 | // AsmDialect, MayLoad, MayStore). |
| 8045 | bool HasSideEffect = IA->hasSideEffects(); |
| 8046 | ExtraFlags (CS); |
| 8047 | |
| 8048 | unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. |
| 8049 | unsigned ResNo = 0; // ResNo - The result number of the next output. |
| 8050 | for (auto &T : TargetConstraints) { |
| 8051 | ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); |
| 8052 | SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); |
| 8053 | |
| 8054 | // Compute the value type for each operand. |
| 8055 | if (OpInfo.Type == InlineAsm::isInput || |
| 8056 | (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { |
| 8057 | OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); |
| 8058 | |
| 8059 | // Process the call argument. BasicBlocks are labels, currently appearing |
| 8060 | // only in asm's. |
| 8061 | const Instruction *I = CS.getInstruction(); |
| 8062 | if (isa<CallBrInst>(I) && |
| 8063 | (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - |
| 8064 | cast<CallBrInst>(I)->getNumIndirectDests())) { |
| 8065 | const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); |
| 8066 | EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); |
| 8067 | OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); |
| 8068 | } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { |
| 8069 | OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); |
| 8070 | } else { |
| 8071 | OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); |
| 8072 | } |
| 8073 | |
| 8074 | OpInfo.ConstraintVT = |
| 8075 | OpInfo |
| 8076 | .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) |
| 8077 | .getSimpleVT(); |
| 8078 | } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { |
| 8079 | // The return value of the call is this value. As such, there is no |
| 8080 | // corresponding argument. |
| 8081 | assert(!CS.getType()->isVoidTy() && "Bad inline asm!" ); |
| 8082 | if (StructType *STy = dyn_cast<StructType>(CS.getType())) { |
| 8083 | OpInfo.ConstraintVT = TLI.getSimpleValueType( |
| 8084 | DAG.getDataLayout(), STy->getElementType(ResNo)); |
| 8085 | } else { |
| 8086 | assert(ResNo == 0 && "Asm only has one result!" ); |
| 8087 | OpInfo.ConstraintVT = |
| 8088 | TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); |
| 8089 | } |
| 8090 | ++ResNo; |
| 8091 | } else { |
| 8092 | OpInfo.ConstraintVT = MVT::Other; |
| 8093 | } |
| 8094 | |
| 8095 | if (!HasSideEffect) |
| 8096 | HasSideEffect = OpInfo.hasMemory(TLI); |
| 8097 | |
| 8098 | // Determine if this InlineAsm MayLoad or MayStore based on the constraints. |
| 8099 | // FIXME: Could we compute this on OpInfo rather than T? |
| 8100 | |
| 8101 | // Compute the constraint code and ConstraintType to use. |
| 8102 | TLI.ComputeConstraintToUse(T, SDValue()); |
| 8103 | |
| 8104 | ExtraInfo.update(T); |
| 8105 | } |
| 8106 | |
| 8107 | |
| 8108 | // We won't need to flush pending loads if this asm doesn't touch |
| 8109 | // memory and is nonvolatile. |
| 8110 | SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); |
| 8111 | |
| 8112 | bool IsCallBr = isa<CallBrInst>(CS.getInstruction()); |
| 8113 | if (IsCallBr) { |
| 8114 | // If this is a callbr we need to flush pending exports since inlineasm_br |
| 8115 | // is a terminator. We need to do this before nodes are glued to |
| 8116 | // the inlineasm_br node. |
| 8117 | Chain = getControlRoot(); |
| 8118 | } |
| 8119 | |
| 8120 | // Second pass over the constraints: compute which constraint option to use. |
| 8121 | for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { |
| 8122 | // If this is an output operand with a matching input operand, look up the |
| 8123 | // matching input. If their types mismatch, e.g. one is an integer, the |
| 8124 | // other is floating point, or their sizes are different, flag it as an |
| 8125 | // error. |
| 8126 | if (OpInfo.hasMatchingInput()) { |
| 8127 | SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; |
| 8128 | patchMatchingInput(OpInfo, Input, DAG); |
| 8129 | } |
| 8130 | |
| 8131 | // Compute the constraint code and ConstraintType to use. |
| 8132 | TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); |
| 8133 | |
| 8134 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 8135 | OpInfo.Type == InlineAsm::isClobber) |
| 8136 | continue; |
| 8137 | |
| 8138 | // If this is a memory input, and if the operand is not indirect, do what we |
| 8139 | // need to provide an address for the memory input. |
| 8140 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 8141 | !OpInfo.isIndirect) { |
| 8142 | assert((OpInfo.isMultipleAlternative || |
| 8143 | (OpInfo.Type == InlineAsm::isInput)) && |
| 8144 | "Can only indirectify direct input operands!" ); |
| 8145 | |
| 8146 | // Memory operands really want the address of the value. |
| 8147 | Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); |
| 8148 | |
| 8149 | // There is no longer a Value* corresponding to this operand. |
| 8150 | OpInfo.CallOperandVal = nullptr; |
| 8151 | |
| 8152 | // It is now an indirect operand. |
| 8153 | OpInfo.isIndirect = true; |
| 8154 | } |
| 8155 | |
| 8156 | } |
| 8157 | |
| 8158 | // AsmNodeOperands - The operands for the ISD::INLINEASM node. |
| 8159 | std::vector<SDValue> AsmNodeOperands; |
| 8160 | AsmNodeOperands.push_back(SDValue()); // reserve space for input chain |
| 8161 | AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( |
| 8162 | IA->getAsmString().c_str(), TLI.getPointerRangeTy(DAG.getDataLayout()))); |
| 8163 | |
| 8164 | // If we have a !srcloc metadata node associated with it, we want to attach |
| 8165 | // this to the ultimately generated inline asm machineinstr. To do this, we |
| 8166 | // pass in the third operand as this (potentially null) inline asm MDNode. |
| 8167 | const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc" ); |
| 8168 | AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); |
| 8169 | |
| 8170 | // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore |
| 8171 | // bits as operand 3. |
| 8172 | AsmNodeOperands.push_back( |
| 8173 | DAG.getTargetConstant(ExtraInfo.get(), getCurSDLoc(), |
| 8174 | TLI.getPointerRangeTy(DAG.getDataLayout()))); |
| 8175 | |
| 8176 | // Third pass: Loop over operands to prepare DAG-level operands.. As part of |
| 8177 | // this, assign virtual and physical registers for inputs and otput. |
| 8178 | for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { |
| 8179 | // Assign Registers. |
| 8180 | SDISelAsmOperandInfo &RefOpInfo = |
| 8181 | OpInfo.isMatchingInputConstraint() |
| 8182 | ? ConstraintOperands[OpInfo.getMatchedOperand()] |
| 8183 | : OpInfo; |
| 8184 | GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); |
| 8185 | |
| 8186 | switch (OpInfo.Type) { |
| 8187 | case InlineAsm::isOutput: |
| 8188 | if (OpInfo.ConstraintType == TargetLowering::C_Memory || |
| 8189 | (OpInfo.ConstraintType == TargetLowering::C_Other && |
| 8190 | OpInfo.isIndirect)) { |
| 8191 | unsigned ConstraintID = |
| 8192 | TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); |
| 8193 | assert(ConstraintID != InlineAsm::Constraint_Unknown && |
| 8194 | "Failed to convert memory constraint code to constraint id." ); |
| 8195 | |
| 8196 | // Add information to the INLINEASM node to know about this output. |
| 8197 | unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); |
| 8198 | OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); |
| 8199 | AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), |
| 8200 | MVT::i32)); |
| 8201 | AsmNodeOperands.push_back(OpInfo.CallOperand); |
| 8202 | break; |
| 8203 | } else if ((OpInfo.ConstraintType == TargetLowering::C_Other && |
| 8204 | !OpInfo.isIndirect) || |
| 8205 | OpInfo.ConstraintType == TargetLowering::C_Register || |
| 8206 | OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { |
| 8207 | // Otherwise, this outputs to a register (directly for C_Register / |
| 8208 | // C_RegisterClass, and a target-defined fashion for C_Other). Find a |
| 8209 | // register that we can use. |
| 8210 | if (OpInfo.AssignedRegs.Regs.empty()) { |
| 8211 | emitInlineAsmError( |
| 8212 | CS, "couldn't allocate output register for constraint '" + |
| 8213 | Twine(OpInfo.ConstraintCode) + "'" ); |
| 8214 | return; |
| 8215 | } |
| 8216 | |
| 8217 | // Add information to the INLINEASM node to know that this register is |
| 8218 | // set. |
| 8219 | OpInfo.AssignedRegs.AddInlineAsmOperands( |
| 8220 | OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber |
| 8221 | : InlineAsm::Kind_RegDef, |
| 8222 | false, 0, getCurSDLoc(), DAG, AsmNodeOperands); |
| 8223 | } |
| 8224 | break; |
| 8225 | |
| 8226 | case InlineAsm::isInput: { |
| 8227 | SDValue InOperandVal = OpInfo.CallOperand; |
| 8228 | |
| 8229 | if (OpInfo.isMatchingInputConstraint()) { |
| 8230 | // If this is required to match an output register we have already set, |
| 8231 | // just use its register. |
| 8232 | auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), |
| 8233 | AsmNodeOperands); |
| 8234 | unsigned OpFlag = |
| 8235 | cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); |
| 8236 | if (InlineAsm::isRegDefKind(OpFlag) || |
| 8237 | InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { |
| 8238 | // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. |
| 8239 | if (OpInfo.isIndirect) { |
| 8240 | // This happens on gcc/testsuite/gcc.dg/pr8788-1.c |
| 8241 | emitInlineAsmError(CS, "inline asm not supported yet:" |
| 8242 | " don't know how to handle tied " |
| 8243 | "indirect register inputs" ); |
| 8244 | return; |
| 8245 | } |
| 8246 | |
| 8247 | MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); |
| 8248 | SmallVector<unsigned, 4> Regs; |
| 8249 | |
| 8250 | if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { |
| 8251 | unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); |
| 8252 | MachineRegisterInfo &RegInfo = |
| 8253 | DAG.getMachineFunction().getRegInfo(); |
| 8254 | for (unsigned i = 0; i != NumRegs; ++i) |
| 8255 | Regs.push_back(RegInfo.createVirtualRegister(RC)); |
| 8256 | } else { |
| 8257 | emitInlineAsmError(CS, "inline asm error: This value type register " |
| 8258 | "class is not natively supported!" ); |
| 8259 | return; |
| 8260 | } |
| 8261 | |
| 8262 | RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); |
| 8263 | |
| 8264 | SDLoc dl = getCurSDLoc(); |
| 8265 | // Use the produced MatchedRegs object to |
| 8266 | MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, |
| 8267 | CS.getInstruction()); |
| 8268 | MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, |
| 8269 | true, OpInfo.getMatchedOperand(), dl, |
| 8270 | DAG, AsmNodeOperands); |
| 8271 | break; |
| 8272 | } |
| 8273 | |
| 8274 | assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!" ); |
| 8275 | assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && |
| 8276 | "Unexpected number of operands" ); |
| 8277 | // Add information to the INLINEASM node to know about this input. |
| 8278 | // See InlineAsm.h isUseOperandTiedToDef. |
| 8279 | OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); |
| 8280 | OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, |
| 8281 | OpInfo.getMatchedOperand()); |
| 8282 | AsmNodeOperands.push_back(DAG.getTargetConstant( |
| 8283 | OpFlag, getCurSDLoc(), TLI.getPointerRangeTy(DAG.getDataLayout()))); |
| 8284 | AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); |
| 8285 | break; |
| 8286 | } |
| 8287 | |
| 8288 | // Treat indirect 'X' constraint as memory. |
| 8289 | if (OpInfo.ConstraintType == TargetLowering::C_Other && |
| 8290 | OpInfo.isIndirect) |
| 8291 | OpInfo.ConstraintType = TargetLowering::C_Memory; |
| 8292 | |
| 8293 | if (OpInfo.ConstraintType == TargetLowering::C_Other) { |
| 8294 | std::vector<SDValue> Ops; |
| 8295 | TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, |
| 8296 | Ops, DAG); |
| 8297 | if (Ops.empty()) { |
| 8298 | emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + |
| 8299 | Twine(OpInfo.ConstraintCode) + "'" ); |
| 8300 | return; |
| 8301 | } |
| 8302 | |
| 8303 | // Add information to the INLINEASM node to know about this input. |
| 8304 | unsigned ResOpType = |
| 8305 | InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); |
| 8306 | AsmNodeOperands.push_back( |
| 8307 | DAG.getTargetConstant(ResOpType, getCurSDLoc(), |
| 8308 | TLI.getPointerRangeTy(DAG.getDataLayout()))); |
| 8309 | AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); |
| 8310 | break; |
| 8311 | } |
| 8312 | |
| 8313 | if (OpInfo.ConstraintType == TargetLowering::C_Memory) { |
| 8314 | assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!" ); |
| 8315 | // FIXME: what is the correct AS here? |
| 8316 | assert(InOperandVal.getValueType() == |
| 8317 | TLI.getPointerTy( |
| 8318 | DAG.getDataLayout(), |
| 8319 | DAG.getDataLayout().getGlobalsAddressSpace()) && |
| 8320 | "Memory operands expect pointer values" ); |
| 8321 | |
| 8322 | unsigned ConstraintID = |
| 8323 | TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); |
| 8324 | assert(ConstraintID != InlineAsm::Constraint_Unknown && |
| 8325 | "Failed to convert memory constraint code to constraint id." ); |
| 8326 | |
| 8327 | // Add information to the INLINEASM node to know about this input. |
| 8328 | unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); |
| 8329 | ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); |
| 8330 | AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, |
| 8331 | getCurSDLoc(), |
| 8332 | MVT::i32)); |
| 8333 | AsmNodeOperands.push_back(InOperandVal); |
| 8334 | break; |
| 8335 | } |
| 8336 | |
| 8337 | assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || |
| 8338 | OpInfo.ConstraintType == TargetLowering::C_Register) && |
| 8339 | "Unknown constraint type!" ); |
| 8340 | |
| 8341 | // TODO: Support this. |
| 8342 | if (OpInfo.isIndirect) { |
| 8343 | emitInlineAsmError( |
| 8344 | CS, "Don't know how to handle indirect register inputs yet " |
| 8345 | "for constraint '" + |
| 8346 | Twine(OpInfo.ConstraintCode) + "'" ); |
| 8347 | return; |
| 8348 | } |
| 8349 | |
| 8350 | // Copy the input into the appropriate registers. |
| 8351 | if (OpInfo.AssignedRegs.Regs.empty()) { |
| 8352 | emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + |
| 8353 | Twine(OpInfo.ConstraintCode) + "'" ); |
| 8354 | return; |
| 8355 | } |
| 8356 | |
| 8357 | SDLoc dl = getCurSDLoc(); |
| 8358 | |
| 8359 | OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, |
| 8360 | Chain, &Flag, CS.getInstruction()); |
| 8361 | |
| 8362 | OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, |
| 8363 | dl, DAG, AsmNodeOperands); |
| 8364 | break; |
| 8365 | } |
| 8366 | case InlineAsm::isClobber: |
| 8367 | // Add the clobbered value to the operand list, so that the register |
| 8368 | // allocator is aware that the physreg got clobbered. |
| 8369 | if (!OpInfo.AssignedRegs.Regs.empty()) |
| 8370 | OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, |
| 8371 | false, 0, getCurSDLoc(), DAG, |
| 8372 | AsmNodeOperands); |
| 8373 | break; |
| 8374 | } |
| 8375 | } |
| 8376 | |
| 8377 | // Finish up input operands. Set the input chain and add the flag last. |
| 8378 | AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; |
| 8379 | if (Flag.getNode()) AsmNodeOperands.push_back(Flag); |
| 8380 | |
| 8381 | unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; |
| 8382 | Chain = DAG.getNode(ISDOpc, getCurSDLoc(), |
| 8383 | DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); |
| 8384 | Flag = Chain.getValue(1); |
| 8385 | |
| 8386 | // Do additional work to generate outputs. |
| 8387 | |
| 8388 | SmallVector<EVT, 1> ResultVTs; |
| 8389 | SmallVector<SDValue, 1> ResultValues; |
| 8390 | SmallVector<SDValue, 8> OutChains; |
| 8391 | |
| 8392 | llvm::Type *CSResultType = CS.getType(); |
| 8393 | ArrayRef<Type *> ResultTypes; |
| 8394 | if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) |
| 8395 | ResultTypes = StructResult->elements(); |
| 8396 | else if (!CSResultType->isVoidTy()) |
| 8397 | ResultTypes = makeArrayRef(CSResultType); |
| 8398 | |
| 8399 | auto CurResultType = ResultTypes.begin(); |
| 8400 | auto handleRegAssign = [&](SDValue V) { |
| 8401 | assert(CurResultType != ResultTypes.end() && "Unexpected value" ); |
| 8402 | assert((*CurResultType)->isSized() && "Unexpected unsized type" ); |
| 8403 | EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); |
| 8404 | ++CurResultType; |
| 8405 | // If the type of the inline asm call site return value is different but has |
| 8406 | // same size as the type of the asm output bitcast it. One example of this |
| 8407 | // is for vectors with different width / number of elements. This can |
| 8408 | // happen for register classes that can contain multiple different value |
| 8409 | // types. The preg or vreg allocated may not have the same VT as was |
| 8410 | // expected. |
| 8411 | // |
| 8412 | // This can also happen for a return value that disagrees with the register |
| 8413 | // class it is put in, eg. a double in a general-purpose register on a |
| 8414 | // 32-bit machine. |
| 8415 | if (ResultVT != V.getValueType() && |
| 8416 | ResultVT.getSizeInBits() == V.getValueSizeInBits()) |
| 8417 | V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); |
| 8418 | else if (ResultVT != V.getValueType() && ResultVT.isInteger() && |
| 8419 | V.getValueType().isInteger()) { |
| 8420 | // If a result value was tied to an input value, the computed result |
| 8421 | // may have a wider width than the expected result. Extract the |
| 8422 | // relevant portion. |
| 8423 | V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); |
| 8424 | } |
| 8425 | assert(ResultVT == V.getValueType() && "Asm result value mismatch!" ); |
| 8426 | ResultVTs.push_back(ResultVT); |
| 8427 | ResultValues.push_back(V); |
| 8428 | }; |
| 8429 | |
| 8430 | // Deal with output operands. |
| 8431 | for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { |
| 8432 | if (OpInfo.Type == InlineAsm::isOutput) { |
| 8433 | SDValue Val; |
| 8434 | // Skip trivial output operands. |
| 8435 | if (OpInfo.AssignedRegs.Regs.empty()) |
| 8436 | continue; |
| 8437 | |
| 8438 | switch (OpInfo.ConstraintType) { |
| 8439 | case TargetLowering::C_Register: |
| 8440 | case TargetLowering::C_RegisterClass: |
| 8441 | Val = OpInfo.AssignedRegs.getCopyFromRegs( |
| 8442 | DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); |
| 8443 | break; |
| 8444 | case TargetLowering::C_Other: |
| 8445 | Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), |
| 8446 | OpInfo, DAG); |
| 8447 | break; |
| 8448 | case TargetLowering::C_Memory: |
| 8449 | break; // Already handled. |
| 8450 | case TargetLowering::C_Unknown: |
| 8451 | assert(false && "Unexpected unknown constraint" ); |
| 8452 | } |
| 8453 | |
| 8454 | // Indirect output manifest as stores. Record output chains. |
| 8455 | if (OpInfo.isIndirect) { |
| 8456 | const Value *Ptr = OpInfo.CallOperandVal; |
| 8457 | assert(Ptr && "Expected value CallOperandVal for indirect asm operand" ); |
| 8458 | SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), |
| 8459 | MachinePointerInfo(Ptr)); |
| 8460 | OutChains.push_back(Store); |
| 8461 | } else { |
| 8462 | // generate CopyFromRegs to associated registers. |
| 8463 | assert(!CS.getType()->isVoidTy() && "Bad inline asm!" ); |
| 8464 | if (Val.getOpcode() == ISD::MERGE_VALUES) { |
| 8465 | for (const SDValue &V : Val->op_values()) |
| 8466 | handleRegAssign(V); |
| 8467 | } else |
| 8468 | handleRegAssign(Val); |
| 8469 | } |
| 8470 | } |
| 8471 | } |
| 8472 | |
| 8473 | // Set results. |
| 8474 | if (!ResultValues.empty()) { |
| 8475 | assert(CurResultType == ResultTypes.end() && |
| 8476 | "Mismatch in number of ResultTypes" ); |
| 8477 | assert(ResultValues.size() == ResultTypes.size() && |
| 8478 | "Mismatch in number of output operands in asm result" ); |
| 8479 | |
| 8480 | SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), |
| 8481 | DAG.getVTList(ResultVTs), ResultValues); |
| 8482 | setValue(CS.getInstruction(), V); |
| 8483 | } |
| 8484 | |
| 8485 | // Collect store chains. |
| 8486 | if (!OutChains.empty()) |
| 8487 | Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); |
| 8488 | |
| 8489 | // Only Update Root if inline assembly has a memory effect. |
| 8490 | if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) |
| 8491 | DAG.setRoot(Chain); |
| 8492 | } |
| 8493 | |
| 8494 | void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, |
| 8495 | const Twine &Message) { |
| 8496 | LLVMContext &Ctx = *DAG.getContext(); |
| 8497 | Ctx.emitError(CS.getInstruction(), Message); |
| 8498 | |
| 8499 | // Make sure we leave the DAG in a valid state |
| 8500 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 8501 | SmallVector<EVT, 1> ValueVTs; |
| 8502 | ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); |
| 8503 | |
| 8504 | if (ValueVTs.empty()) |
| 8505 | return; |
| 8506 | |
| 8507 | SmallVector<SDValue, 1> Ops; |
| 8508 | for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) |
| 8509 | Ops.push_back(DAG.getUNDEF(ValueVTs[i])); |
| 8510 | |
| 8511 | setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); |
| 8512 | } |
| 8513 | |
| 8514 | void SelectionDAGBuilder::visitVAStart(const CallInst &I) { |
| 8515 | DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), |
| 8516 | MVT::Other, getRoot(), |
| 8517 | getValue(I.getArgOperand(0)), |
| 8518 | DAG.getSrcValue(I.getArgOperand(0)))); |
| 8519 | } |
| 8520 | |
| 8521 | void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { |
| 8522 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 8523 | const DataLayout &DL = DAG.getDataLayout(); |
| 8524 | SDValue V = DAG.getVAArg( |
| 8525 | TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), |
| 8526 | getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), |
| 8527 | DL.getABITypeAlignment(I.getType())); |
| 8528 | DAG.setRoot(V.getValue(1)); |
| 8529 | |
| 8530 | if (I.getType()->isPointerTy()) |
| 8531 | V = DAG.getPtrExtOrTrunc( |
| 8532 | V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); |
| 8533 | setValue(&I, V); |
| 8534 | } |
| 8535 | |
| 8536 | void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { |
| 8537 | DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), |
| 8538 | MVT::Other, getRoot(), |
| 8539 | getValue(I.getArgOperand(0)), |
| 8540 | DAG.getSrcValue(I.getArgOperand(0)))); |
| 8541 | } |
| 8542 | |
| 8543 | void SelectionDAGBuilder::visitVACopy(const CallInst &I) { |
| 8544 | DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), |
| 8545 | MVT::Other, getRoot(), |
| 8546 | getValue(I.getArgOperand(0)), |
| 8547 | getValue(I.getArgOperand(1)), |
| 8548 | DAG.getSrcValue(I.getArgOperand(0)), |
| 8549 | DAG.getSrcValue(I.getArgOperand(1)))); |
| 8550 | } |
| 8551 | |
| 8552 | SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, |
| 8553 | const Instruction &I, |
| 8554 | SDValue Op) { |
| 8555 | const MDNode *Range = I.getMetadata(LLVMContext::MD_range); |
| 8556 | if (!Range) |
| 8557 | return Op; |
| 8558 | |
| 8559 | ConstantRange CR = getConstantRangeFromMetadata(*Range); |
| 8560 | if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) |
| 8561 | return Op; |
| 8562 | |
| 8563 | APInt Lo = CR.getUnsignedMin(); |
| 8564 | if (!Lo.isMinValue()) |
| 8565 | return Op; |
| 8566 | |
| 8567 | APInt Hi = CR.getUnsignedMax(); |
| 8568 | unsigned Bits = std::max(Hi.getActiveBits(), |
| 8569 | static_cast<unsigned>(IntegerType::MIN_INT_BITS)); |
| 8570 | |
| 8571 | EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); |
| 8572 | |
| 8573 | SDLoc SL = getCurSDLoc(); |
| 8574 | |
| 8575 | SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, |
| 8576 | DAG.getValueType(SmallVT)); |
| 8577 | unsigned NumVals = Op.getNode()->getNumValues(); |
| 8578 | if (NumVals == 1) |
| 8579 | return ZExt; |
| 8580 | |
| 8581 | SmallVector<SDValue, 4> Ops; |
| 8582 | |
| 8583 | Ops.push_back(ZExt); |
| 8584 | for (unsigned I = 1; I != NumVals; ++I) |
| 8585 | Ops.push_back(Op.getValue(I)); |
| 8586 | |
| 8587 | return DAG.getMergeValues(Ops, SL); |
| 8588 | } |
| 8589 | |
| 8590 | /// Populate a CallLowerinInfo (into \p CLI) based on the properties of |
| 8591 | /// the call being lowered. |
| 8592 | /// |
| 8593 | /// This is a helper for lowering intrinsics that follow a target calling |
| 8594 | /// convention or require stack pointer adjustment. Only a subset of the |
| 8595 | /// intrinsic's operands need to participate in the calling convention. |
| 8596 | void SelectionDAGBuilder::populateCallLoweringInfo( |
| 8597 | TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, |
| 8598 | unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, |
| 8599 | bool IsPatchPoint) { |
| 8600 | TargetLowering::ArgListTy Args; |
| 8601 | Args.reserve(NumArgs); |
| 8602 | |
| 8603 | // Populate the argument list. |
| 8604 | // Attributes for args start at offset 1, after the return attribute. |
| 8605 | for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; |
| 8606 | ArgI != ArgE; ++ArgI) { |
| 8607 | const Value *V = Call->getOperand(ArgI); |
| 8608 | |
| 8609 | assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic." ); |
| 8610 | |
| 8611 | TargetLowering::ArgListEntry Entry; |
| 8612 | Entry.Node = getValue(V); |
| 8613 | Entry.Ty = V->getType(); |
| 8614 | Entry.setAttributes(Call, ArgI); |
| 8615 | Args.push_back(Entry); |
| 8616 | } |
| 8617 | |
| 8618 | CLI.setDebugLoc(getCurSDLoc()) |
| 8619 | .setChain(getRoot()) |
| 8620 | .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) |
| 8621 | .setDiscardResult(Call->use_empty()) |
| 8622 | .setIsPatchPoint(IsPatchPoint); |
| 8623 | } |
| 8624 | |
| 8625 | /// Add a stack map intrinsic call's live variable operands to a stackmap |
| 8626 | /// or patchpoint target node's operand list. |
| 8627 | /// |
| 8628 | /// Constants are converted to TargetConstants purely as an optimization to |
| 8629 | /// avoid constant materialization and register allocation. |
| 8630 | /// |
| 8631 | /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not |
| 8632 | /// generate addess computation nodes, and so ExpandISelPseudo can convert the |
| 8633 | /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids |
| 8634 | /// address materialization and register allocation, but may also be required |
| 8635 | /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an |
| 8636 | /// alloca in the entry block, then the runtime may assume that the alloca's |
| 8637 | /// StackMap location can be read immediately after compilation and that the |
| 8638 | /// location is valid at any point during execution (this is similar to the |
| 8639 | /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were |
| 8640 | /// only available in a register, then the runtime would need to trap when |
| 8641 | /// execution reaches the StackMap in order to read the alloca's location. |
| 8642 | static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, |
| 8643 | const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, |
| 8644 | SelectionDAGBuilder &Builder) { |
| 8645 | for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { |
| 8646 | SDValue OpVal = Builder.getValue(CS.getArgument(i)); |
| 8647 | if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { |
| 8648 | Ops.push_back( |
| 8649 | Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); |
| 8650 | Ops.push_back( |
| 8651 | Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); |
| 8652 | } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { |
| 8653 | const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); |
| 8654 | Ops.push_back(Builder.DAG.getTargetFrameIndex( |
| 8655 | FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); |
| 8656 | } else |
| 8657 | Ops.push_back(OpVal); |
| 8658 | } |
| 8659 | } |
| 8660 | |
| 8661 | /// Lower llvm.experimental.stackmap directly to its target opcode. |
| 8662 | void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { |
| 8663 | // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, |
| 8664 | // [live variables...]) |
| 8665 | |
| 8666 | assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value." ); |
| 8667 | |
| 8668 | SDValue Chain, InFlag, Callee, NullPtr; |
| 8669 | SmallVector<SDValue, 32> Ops; |
| 8670 | |
| 8671 | SDLoc DL = getCurSDLoc(); |
| 8672 | Callee = getValue(CI.getCalledValue()); |
| 8673 | NullPtr = DAG.getIntPtrConstant(0, DL, true); |
| 8674 | |
| 8675 | // The stackmap intrinsic only records the live variables (the arguemnts |
| 8676 | // passed to it) and emits NOPS (if requested). Unlike the patchpoint |
| 8677 | // intrinsic, this won't be lowered to a function call. This means we don't |
| 8678 | // have to worry about calling conventions and target specific lowering code. |
| 8679 | // Instead we perform the call lowering right here. |
| 8680 | // |
| 8681 | // chain, flag = CALLSEQ_START(chain, 0, 0) |
| 8682 | // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) |
| 8683 | // chain, flag = CALLSEQ_END(chain, 0, 0, flag) |
| 8684 | // |
| 8685 | Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); |
| 8686 | InFlag = Chain.getValue(1); |
| 8687 | |
| 8688 | // Add the <id> and <numBytes> constants. |
| 8689 | SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); |
| 8690 | Ops.push_back(DAG.getTargetConstant( |
| 8691 | cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); |
| 8692 | SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); |
| 8693 | Ops.push_back(DAG.getTargetConstant( |
| 8694 | cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, |
| 8695 | MVT::i32)); |
| 8696 | |
| 8697 | // Push live variables for the stack map. |
| 8698 | addStackMapLiveVars(&CI, 2, DL, Ops, *this); |
| 8699 | |
| 8700 | // We are not pushing any register mask info here on the operands list, |
| 8701 | // because the stackmap doesn't clobber anything. |
| 8702 | |
| 8703 | // Push the chain and the glue flag. |
| 8704 | Ops.push_back(Chain); |
| 8705 | Ops.push_back(InFlag); |
| 8706 | |
| 8707 | // Create the STACKMAP node. |
| 8708 | SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); |
| 8709 | SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); |
| 8710 | Chain = SDValue(SM, 0); |
| 8711 | InFlag = Chain.getValue(1); |
| 8712 | |
| 8713 | Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); |
| 8714 | |
| 8715 | // Stackmaps don't generate values, so nothing goes into the NodeMap. |
| 8716 | |
| 8717 | // Set the root to the target-lowered call chain. |
| 8718 | DAG.setRoot(Chain); |
| 8719 | |
| 8720 | // Inform the Frame Information that we have a stackmap in this function. |
| 8721 | FuncInfo.MF->getFrameInfo().setHasStackMap(); |
| 8722 | } |
| 8723 | |
| 8724 | /// Lower llvm.experimental.patchpoint directly to its target opcode. |
| 8725 | void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, |
| 8726 | const BasicBlock *EHPadBB) { |
| 8727 | // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, |
| 8728 | // i32 <numBytes>, |
| 8729 | // i8* <target>, |
| 8730 | // i32 <numArgs>, |
| 8731 | // [Args...], |
| 8732 | // [live variables...]) |
| 8733 | |
| 8734 | CallingConv::ID CC = CS.getCallingConv(); |
| 8735 | bool IsAnyRegCC = CC == CallingConv::AnyReg; |
| 8736 | bool HasDef = !CS->getType()->isVoidTy(); |
| 8737 | SDLoc dl = getCurSDLoc(); |
| 8738 | SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); |
| 8739 | |
| 8740 | // Handle immediate and symbolic callees. |
| 8741 | if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) |
| 8742 | Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, |
| 8743 | /*isTarget=*/true); |
| 8744 | else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) |
| 8745 | Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), |
| 8746 | SDLoc(SymbolicCallee), |
| 8747 | SymbolicCallee->getValueType(0)); |
| 8748 | |
| 8749 | // Get the real number of arguments participating in the call <numArgs> |
| 8750 | SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); |
| 8751 | unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); |
| 8752 | |
| 8753 | // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> |
| 8754 | // Intrinsics include all meta-operands up to but not including CC. |
| 8755 | unsigned NumMetaOpers = PatchPointOpers::CCPos; |
| 8756 | assert(CS.arg_size() >= NumMetaOpers + NumArgs && |
| 8757 | "Not enough arguments provided to the patchpoint intrinsic" ); |
| 8758 | |
| 8759 | // For AnyRegCC the arguments are lowered later on manually. |
| 8760 | unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; |
| 8761 | Type *ReturnTy = |
| 8762 | IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); |
| 8763 | |
| 8764 | TargetLowering::CallLoweringInfo CLI(DAG); |
| 8765 | populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), |
| 8766 | NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); |
| 8767 | std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); |
| 8768 | |
| 8769 | SDNode *CallEnd = Result.second.getNode(); |
| 8770 | if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) |
| 8771 | CallEnd = CallEnd->getOperand(0).getNode(); |
| 8772 | |
| 8773 | /// Get a call instruction from the call sequence chain. |
| 8774 | /// Tail calls are not allowed. |
| 8775 | assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && |
| 8776 | "Expected a callseq node." ); |
| 8777 | SDNode *Call = CallEnd->getOperand(0).getNode(); |
| 8778 | bool HasGlue = Call->getGluedNode(); |
| 8779 | |
| 8780 | // Replace the target specific call node with the patchable intrinsic. |
| 8781 | SmallVector<SDValue, 8> Ops; |
| 8782 | |
| 8783 | // Add the <id> and <numBytes> constants. |
| 8784 | SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); |
| 8785 | Ops.push_back(DAG.getTargetConstant( |
| 8786 | cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); |
| 8787 | SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); |
| 8788 | Ops.push_back(DAG.getTargetConstant( |
| 8789 | cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, |
| 8790 | MVT::i32)); |
| 8791 | |
| 8792 | // Add the callee. |
| 8793 | Ops.push_back(Callee); |
| 8794 | |
| 8795 | // Adjust <numArgs> to account for any arguments that have been passed on the |
| 8796 | // stack instead. |
| 8797 | // Call Node: Chain, Target, {Args}, RegMask, [Glue] |
| 8798 | unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); |
| 8799 | NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; |
| 8800 | Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); |
| 8801 | |
| 8802 | // Add the calling convention |
| 8803 | Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); |
| 8804 | |
| 8805 | // Add the arguments we omitted previously. The register allocator should |
| 8806 | // place these in any free register. |
| 8807 | if (IsAnyRegCC) |
| 8808 | for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) |
| 8809 | Ops.push_back(getValue(CS.getArgument(i))); |
| 8810 | |
| 8811 | // Push the arguments from the call instruction up to the register mask. |
| 8812 | SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; |
| 8813 | Ops.append(Call->op_begin() + 2, e); |
| 8814 | |
| 8815 | // Push live variables for the stack map. |
| 8816 | addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); |
| 8817 | |
| 8818 | // Push the register mask info. |
| 8819 | if (HasGlue) |
| 8820 | Ops.push_back(*(Call->op_end()-2)); |
| 8821 | else |
| 8822 | Ops.push_back(*(Call->op_end()-1)); |
| 8823 | |
| 8824 | // Push the chain (this is originally the first operand of the call, but |
| 8825 | // becomes now the last or second to last operand). |
| 8826 | Ops.push_back(*(Call->op_begin())); |
| 8827 | |
| 8828 | // Push the glue flag (last operand). |
| 8829 | if (HasGlue) |
| 8830 | Ops.push_back(*(Call->op_end()-1)); |
| 8831 | |
| 8832 | SDVTList NodeTys; |
| 8833 | if (IsAnyRegCC && HasDef) { |
| 8834 | // Create the return types based on the intrinsic definition |
| 8835 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 8836 | SmallVector<EVT, 3> ValueVTs; |
| 8837 | ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); |
| 8838 | assert(ValueVTs.size() == 1 && "Expected only one return value type." ); |
| 8839 | |
| 8840 | // There is always a chain and a glue type at the end |
| 8841 | ValueVTs.push_back(MVT::Other); |
| 8842 | ValueVTs.push_back(MVT::Glue); |
| 8843 | NodeTys = DAG.getVTList(ValueVTs); |
| 8844 | } else |
| 8845 | NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); |
| 8846 | |
| 8847 | // Replace the target specific call node with a PATCHPOINT node. |
| 8848 | MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, |
| 8849 | dl, NodeTys, Ops); |
| 8850 | |
| 8851 | // Update the NodeMap. |
| 8852 | if (HasDef) { |
| 8853 | if (IsAnyRegCC) |
| 8854 | setValue(CS.getInstruction(), SDValue(MN, 0)); |
| 8855 | else |
| 8856 | setValue(CS.getInstruction(), Result.first); |
| 8857 | } |
| 8858 | |
| 8859 | // Fixup the consumers of the intrinsic. The chain and glue may be used in the |
| 8860 | // call sequence. Furthermore the location of the chain and glue can change |
| 8861 | // when the AnyReg calling convention is used and the intrinsic returns a |
| 8862 | // value. |
| 8863 | if (IsAnyRegCC && HasDef) { |
| 8864 | SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; |
| 8865 | SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; |
| 8866 | DAG.ReplaceAllUsesOfValuesWith(From, To, 2); |
| 8867 | } else |
| 8868 | DAG.ReplaceAllUsesWith(Call, MN); |
| 8869 | DAG.DeleteNode(Call); |
| 8870 | |
| 8871 | // Inform the Frame Information that we have a patchpoint in this function. |
| 8872 | FuncInfo.MF->getFrameInfo().setHasPatchPoint(); |
| 8873 | } |
| 8874 | |
| 8875 | void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, |
| 8876 | unsigned Intrinsic) { |
| 8877 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 8878 | SDValue Op1 = getValue(I.getArgOperand(0)); |
| 8879 | SDValue Op2; |
| 8880 | if (I.getNumArgOperands() > 1) |
| 8881 | Op2 = getValue(I.getArgOperand(1)); |
| 8882 | SDLoc dl = getCurSDLoc(); |
| 8883 | EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); |
| 8884 | SDValue Res; |
| 8885 | FastMathFlags FMF; |
| 8886 | if (isa<FPMathOperator>(I)) |
| 8887 | FMF = I.getFastMathFlags(); |
| 8888 | |
| 8889 | switch (Intrinsic) { |
| 8890 | case Intrinsic::experimental_vector_reduce_v2_fadd: |
| 8891 | if (FMF.allowReassoc()) |
| 8892 | Res = DAG.getNode(ISD::FADD, dl, VT, Op1, |
| 8893 | DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); |
| 8894 | else |
| 8895 | Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); |
| 8896 | break; |
| 8897 | case Intrinsic::experimental_vector_reduce_v2_fmul: |
| 8898 | if (FMF.allowReassoc()) |
| 8899 | Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, |
| 8900 | DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); |
| 8901 | else |
| 8902 | Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); |
| 8903 | break; |
| 8904 | case Intrinsic::experimental_vector_reduce_add: |
| 8905 | Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); |
| 8906 | break; |
| 8907 | case Intrinsic::experimental_vector_reduce_mul: |
| 8908 | Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); |
| 8909 | break; |
| 8910 | case Intrinsic::experimental_vector_reduce_and: |
| 8911 | Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); |
| 8912 | break; |
| 8913 | case Intrinsic::experimental_vector_reduce_or: |
| 8914 | Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); |
| 8915 | break; |
| 8916 | case Intrinsic::experimental_vector_reduce_xor: |
| 8917 | Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); |
| 8918 | break; |
| 8919 | case Intrinsic::experimental_vector_reduce_smax: |
| 8920 | Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); |
| 8921 | break; |
| 8922 | case Intrinsic::experimental_vector_reduce_smin: |
| 8923 | Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); |
| 8924 | break; |
| 8925 | case Intrinsic::experimental_vector_reduce_umax: |
| 8926 | Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); |
| 8927 | break; |
| 8928 | case Intrinsic::experimental_vector_reduce_umin: |
| 8929 | Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); |
| 8930 | break; |
| 8931 | case Intrinsic::experimental_vector_reduce_fmax: |
| 8932 | Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); |
| 8933 | break; |
| 8934 | case Intrinsic::experimental_vector_reduce_fmin: |
| 8935 | Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); |
| 8936 | break; |
| 8937 | default: |
| 8938 | llvm_unreachable("Unhandled vector reduce intrinsic" ); |
| 8939 | } |
| 8940 | setValue(&I, Res); |
| 8941 | } |
| 8942 | |
| 8943 | /// Returns an AttributeList representing the attributes applied to the return |
| 8944 | /// value of the given call. |
| 8945 | static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { |
| 8946 | SmallVector<Attribute::AttrKind, 2> Attrs; |
| 8947 | if (CLI.RetSExt) |
| 8948 | Attrs.push_back(Attribute::SExt); |
| 8949 | if (CLI.RetZExt) |
| 8950 | Attrs.push_back(Attribute::ZExt); |
| 8951 | if (CLI.IsInReg) |
| 8952 | Attrs.push_back(Attribute::InReg); |
| 8953 | |
| 8954 | return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, |
| 8955 | Attrs); |
| 8956 | } |
| 8957 | |
| 8958 | /// TargetLowering::LowerCallTo - This is the default LowerCallTo |
| 8959 | /// implementation, which just calls LowerCall. |
| 8960 | /// FIXME: When all targets are |
| 8961 | /// migrated to using LowerCall, this hook should be integrated into SDISel. |
| 8962 | std::pair<SDValue, SDValue> |
| 8963 | TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { |
| 8964 | // Handle the incoming return values from the call. |
| 8965 | CLI.Ins.clear(); |
| 8966 | Type *OrigRetTy = CLI.RetTy; |
| 8967 | SmallVector<EVT, 4> RetTys; |
| 8968 | SmallVector<uint64_t, 4> Offsets; |
| 8969 | auto &DL = CLI.DAG.getDataLayout(); |
| 8970 | ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); |
| 8971 | |
| 8972 | if (CLI.IsPostTypeLegalization) { |
| 8973 | // If we are lowering a libcall after legalization, split the return type. |
| 8974 | SmallVector<EVT, 4> OldRetTys; |
| 8975 | SmallVector<uint64_t, 4> OldOffsets; |
| 8976 | RetTys.swap(OldRetTys); |
| 8977 | Offsets.swap(OldOffsets); |
| 8978 | |
| 8979 | for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { |
| 8980 | EVT RetVT = OldRetTys[i]; |
| 8981 | uint64_t Offset = OldOffsets[i]; |
| 8982 | MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); |
| 8983 | unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); |
| 8984 | unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; |
| 8985 | RetTys.append(NumRegs, RegisterVT); |
| 8986 | for (unsigned j = 0; j != NumRegs; ++j) |
| 8987 | Offsets.push_back(Offset + j * RegisterVTByteSZ); |
| 8988 | } |
| 8989 | } |
| 8990 | |
| 8991 | SmallVector<ISD::OutputArg, 4> Outs; |
| 8992 | GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); |
| 8993 | |
| 8994 | bool CanLowerReturn = |
| 8995 | this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), |
| 8996 | CLI.IsVarArg, Outs, CLI.RetTy->getContext()); |
| 8997 | |
| 8998 | SDValue DemoteStackSlot; |
| 8999 | int DemoteStackIdx = -100; |
| 9000 | if (!CanLowerReturn) { |
| 9001 | // FIXME: equivalent assert? |
| 9002 | // assert(!CS.hasInAllocaArgument() && |
| 9003 | // "sret demotion is incompatible with inalloca"); |
| 9004 | uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); |
| 9005 | unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); |
| 9006 | MachineFunction &MF = CLI.DAG.getMachineFunction(); |
| 9007 | DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); |
| 9008 | Type *StackSlotPtrType = PointerType::get(CLI.RetTy, |
| 9009 | DL.getAllocaAddrSpace()); |
| 9010 | |
| 9011 | DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); |
| 9012 | ArgListEntry Entry; |
| 9013 | Entry.Node = DemoteStackSlot; |
| 9014 | Entry.Ty = StackSlotPtrType; |
| 9015 | Entry.IsSExt = false; |
| 9016 | Entry.IsZExt = false; |
| 9017 | Entry.IsInReg = false; |
| 9018 | Entry.IsSRet = true; |
| 9019 | Entry.IsNest = false; |
| 9020 | Entry.IsByVal = false; |
| 9021 | Entry.IsReturned = false; |
| 9022 | Entry.IsSwiftSelf = false; |
| 9023 | Entry.IsSwiftError = false; |
| 9024 | Entry.Alignment = Align; |
| 9025 | CLI.getArgs().insert(CLI.getArgs().begin(), Entry); |
| 9026 | CLI.NumFixedArgs += 1; |
| 9027 | CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); |
| 9028 | |
| 9029 | // sret demotion isn't compatible with tail-calls, since the sret argument |
| 9030 | // points into the callers stack frame. |
| 9031 | CLI.IsTailCall = false; |
| 9032 | } else { |
| 9033 | bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( |
| 9034 | CLI.RetTy, CLI.CallConv, CLI.IsVarArg); |
| 9035 | for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { |
| 9036 | ISD::ArgFlagsTy Flags; |
| 9037 | if (NeedsRegBlock) { |
| 9038 | Flags.setInConsecutiveRegs(); |
| 9039 | if (I == RetTys.size() - 1) |
| 9040 | Flags.setInConsecutiveRegsLast(); |
| 9041 | } |
| 9042 | EVT VT = RetTys[I]; |
| 9043 | MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), |
| 9044 | CLI.CallConv, VT); |
| 9045 | unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), |
| 9046 | CLI.CallConv, VT); |
| 9047 | for (unsigned i = 0; i != NumRegs; ++i) { |
| 9048 | ISD::InputArg MyFlags; |
| 9049 | MyFlags.Flags = Flags; |
| 9050 | MyFlags.VT = RegisterVT; |
| 9051 | MyFlags.ArgVT = VT; |
| 9052 | MyFlags.Used = CLI.IsReturnValueUsed; |
| 9053 | if (CLI.RetTy->isPointerTy()) { |
| 9054 | MyFlags.Flags.setPointer(); |
| 9055 | MyFlags.Flags.setPointerAddrSpace( |
| 9056 | cast<PointerType>(CLI.RetTy)->getAddressSpace()); |
| 9057 | } |
| 9058 | if (CLI.RetSExt) |
| 9059 | MyFlags.Flags.setSExt(); |
| 9060 | if (CLI.RetZExt) |
| 9061 | MyFlags.Flags.setZExt(); |
| 9062 | if (CLI.IsInReg) |
| 9063 | MyFlags.Flags.setInReg(); |
| 9064 | CLI.Ins.push_back(MyFlags); |
| 9065 | } |
| 9066 | } |
| 9067 | } |
| 9068 | |
| 9069 | // We push in swifterror return as the last element of CLI.Ins. |
| 9070 | ArgListTy &Args = CLI.getArgs(); |
| 9071 | if (supportSwiftError()) { |
| 9072 | for (unsigned i = 0, e = Args.size(); i != e; ++i) { |
| 9073 | if (Args[i].IsSwiftError) { |
| 9074 | ISD::InputArg MyFlags; |
| 9075 | MyFlags.VT = getPointerRangeTy(DL); |
| 9076 | MyFlags.ArgVT = EVT(getPointerRangeTy(DL)); |
| 9077 | MyFlags.Flags.setSwiftError(); |
| 9078 | CLI.Ins.push_back(MyFlags); |
| 9079 | } |
| 9080 | } |
| 9081 | } |
| 9082 | |
| 9083 | // Handle all of the outgoing arguments. |
| 9084 | CLI.Outs.clear(); |
| 9085 | CLI.OutVals.clear(); |
| 9086 | for (unsigned i = 0, e = Args.size(); i != e; ++i) { |
| 9087 | SmallVector<EVT, 4> ValueVTs; |
| 9088 | ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); |
| 9089 | // FIXME: Split arguments if CLI.IsPostTypeLegalization |
| 9090 | Type *FinalType = Args[i].Ty; |
| 9091 | // Ignore byval attribute on CHERI capability arguments because we just |
| 9092 | // pass them in capability registers |
| 9093 | bool isArgCHERICapability = FinalType->isPointerTy() && |
| 9094 | DL.isFatPointer(FinalType->getPointerAddressSpace()); |
| 9095 | if (Args[i].IsByVal && !isArgCHERICapability) |
| 9096 | FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); |
| 9097 | bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( |
| 9098 | FinalType, CLI.CallConv, CLI.IsVarArg); |
| 9099 | for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; |
| 9100 | ++Value) { |
| 9101 | EVT VT = ValueVTs[Value]; |
| 9102 | Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); |
| 9103 | SDValue Op = SDValue(Args[i].Node.getNode(), |
| 9104 | Args[i].Node.getResNo() + Value); |
| 9105 | ISD::ArgFlagsTy Flags; |
| 9106 | |
| 9107 | // Certain targets (such as MIPS), may have a different ABI alignment |
| 9108 | // for a type depending on the context. Give the target a chance to |
| 9109 | // specify the alignment it wants. |
| 9110 | unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); |
| 9111 | |
| 9112 | if (Args[i].Ty->isPointerTy()) { |
| 9113 | Flags.setPointer(); |
| 9114 | Flags.setPointerAddrSpace( |
| 9115 | cast<PointerType>(Args[i].Ty)->getAddressSpace()); |
| 9116 | } |
| 9117 | if (Args[i].IsZExt) |
| 9118 | Flags.setZExt(); |
| 9119 | if (Args[i].IsSExt) |
| 9120 | Flags.setSExt(); |
| 9121 | if (Args[i].IsInReg) { |
| 9122 | // If we are using vectorcall calling convention, a structure that is |
| 9123 | // passed InReg - is surely an HVA |
| 9124 | if (CLI.CallConv == CallingConv::X86_VectorCall && |
| 9125 | isa<StructType>(FinalType)) { |
| 9126 | // The first value of a structure is marked |
| 9127 | if (0 == Value) |
| 9128 | Flags.setHvaStart(); |
| 9129 | Flags.setHva(); |
| 9130 | } |
| 9131 | // Set InReg Flag |
| 9132 | Flags.setInReg(); |
| 9133 | } |
| 9134 | if (Args[i].IsSRet) |
| 9135 | Flags.setSRet(); |
| 9136 | if (Args[i].IsSwiftSelf) |
| 9137 | Flags.setSwiftSelf(); |
| 9138 | if (Args[i].IsSwiftError) |
| 9139 | Flags.setSwiftError(); |
| 9140 | if (Args[i].IsByVal && !isArgCHERICapability) |
| 9141 | Flags.setByVal(); |
| 9142 | if (Args[i].IsInAlloca) { |
| 9143 | Flags.setInAlloca(); |
| 9144 | // Set the byval flag for CCAssignFn callbacks that don't know about |
| 9145 | // inalloca. This way we can know how many bytes we should've allocated |
| 9146 | // and how many bytes a callee cleanup function will pop. If we port |
| 9147 | // inalloca to more targets, we'll have to add custom inalloca handling |
| 9148 | // in the various CC lowering callbacks. |
| 9149 | Flags.setByVal(); |
| 9150 | } |
| 9151 | if ((Args[i].IsByVal && !isArgCHERICapability) || Args[i].IsInAlloca) { |
| 9152 | PointerType *Ty = cast<PointerType>(Args[i].Ty); |
| 9153 | Type *ElementTy = Ty->getElementType(); |
| 9154 | |
| 9155 | unsigned FrameSize = DL.getTypeAllocSize( |
| 9156 | Args[i].ByValType ? Args[i].ByValType : ElementTy); |
| 9157 | Flags.setByValSize(FrameSize); |
| 9158 | |
| 9159 | // info is not there but there are cases it cannot get right. |
| 9160 | unsigned FrameAlign; |
| 9161 | if (Args[i].Alignment) |
| 9162 | FrameAlign = Args[i].Alignment; |
| 9163 | else |
| 9164 | FrameAlign = getByValTypeAlignment(ElementTy, DL); |
| 9165 | Flags.setByValAlign(FrameAlign); |
| 9166 | } |
| 9167 | if (Args[i].IsNest) |
| 9168 | Flags.setNest(); |
| 9169 | if (NeedsRegBlock) |
| 9170 | Flags.setInConsecutiveRegs(); |
| 9171 | Flags.setOrigAlign(OriginalAlignment); |
| 9172 | |
| 9173 | MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), |
| 9174 | CLI.CallConv, VT); |
| 9175 | unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), |
| 9176 | CLI.CallConv, VT); |
| 9177 | SmallVector<SDValue, 4> Parts(NumParts); |
| 9178 | ISD::NodeType ExtendKind = ISD::ANY_EXTEND; |
| 9179 | |
| 9180 | if (Args[i].IsSExt) |
| 9181 | ExtendKind = ISD::SIGN_EXTEND; |
| 9182 | else if (Args[i].IsZExt) |
| 9183 | ExtendKind = ISD::ZERO_EXTEND; |
| 9184 | |
| 9185 | // Conservatively only handle 'returned' on non-vectors that can be lowered, |
| 9186 | // for now. |
| 9187 | if (Args[i].IsReturned && !Op.getValueType().isVector() && |
| 9188 | CanLowerReturn) { |
| 9189 | assert((CLI.RetTy == Args[i].Ty || |
| 9190 | (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && |
| 9191 | CLI.RetTy->getPointerAddressSpace() == |
| 9192 | Args[i].Ty->getPointerAddressSpace())) && |
| 9193 | RetTys.size() == NumValues && "unexpected use of 'returned'" ); |
| 9194 | // Before passing 'returned' to the target lowering code, ensure that |
| 9195 | // either the register MVT and the actual EVT are the same size or that |
| 9196 | // the return value and argument are extended in the same way; in these |
| 9197 | // cases it's safe to pass the argument register value unchanged as the |
| 9198 | // return register value (although it's at the target's option whether |
| 9199 | // to do so) |
| 9200 | // TODO: allow code generation to take advantage of partially preserved |
| 9201 | // registers rather than clobbering the entire register when the |
| 9202 | // parameter extension method is not compatible with the return |
| 9203 | // extension method |
| 9204 | if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || |
| 9205 | (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && |
| 9206 | CLI.RetZExt == Args[i].IsZExt)) |
| 9207 | Flags.setReturned(); |
| 9208 | } |
| 9209 | |
| 9210 | getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, |
| 9211 | CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); |
| 9212 | |
| 9213 | for (unsigned j = 0; j != NumParts; ++j) { |
| 9214 | // if it isn't first piece, alignment must be 1 |
| 9215 | ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, |
| 9216 | i < CLI.NumFixedArgs, |
| 9217 | i, j*Parts[j].getValueType().getStoreSize()); |
| 9218 | if (NumParts > 1 && j == 0) |
| 9219 | MyFlags.Flags.setSplit(); |
| 9220 | else if (j != 0) { |
| 9221 | MyFlags.Flags.setOrigAlign(1); |
| 9222 | if (j == NumParts - 1) |
| 9223 | MyFlags.Flags.setSplitEnd(); |
| 9224 | } |
| 9225 | |
| 9226 | CLI.Outs.push_back(MyFlags); |
| 9227 | CLI.OutVals.push_back(Parts[j]); |
| 9228 | } |
| 9229 | |
| 9230 | if (NeedsRegBlock && Value == NumValues - 1) |
| 9231 | CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); |
| 9232 | } |
| 9233 | } |
| 9234 | |
| 9235 | SmallVector<SDValue, 4> InVals; |
| 9236 | CLI.Chain = LowerCall(CLI, InVals); |
| 9237 | |
| 9238 | // Update CLI.InVals to use outside of this function. |
| 9239 | CLI.InVals = InVals; |
| 9240 | |
| 9241 | // Verify that the target's LowerCall behaved as expected. |
| 9242 | assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && |
| 9243 | "LowerCall didn't return a valid chain!" ); |
| 9244 | assert((!CLI.IsTailCall || InVals.empty()) && |
| 9245 | "LowerCall emitted a return value for a tail call!" ); |
| 9246 | assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && |
| 9247 | "LowerCall didn't emit the correct number of values!" ); |
| 9248 | |
| 9249 | // For a tail call, the return value is merely live-out and there aren't |
| 9250 | // any nodes in the DAG representing it. Return a special value to |
| 9251 | // indicate that a tail call has been emitted and no more Instructions |
| 9252 | // should be processed in the current block. |
| 9253 | if (CLI.IsTailCall) { |
| 9254 | CLI.DAG.setRoot(CLI.Chain); |
| 9255 | return std::make_pair(SDValue(), SDValue()); |
| 9256 | } |
| 9257 | |
| 9258 | #ifndef NDEBUG |
| 9259 | for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { |
| 9260 | assert(InVals[i].getNode() && "LowerCall emitted a null value!" ); |
| 9261 | assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && |
| 9262 | "LowerCall emitted a value with the wrong type!" ); |
| 9263 | } |
| 9264 | #endif |
| 9265 | |
| 9266 | SmallVector<SDValue, 4> ReturnValues; |
| 9267 | if (!CanLowerReturn) { |
| 9268 | // The instruction result is the result of loading from the |
| 9269 | // hidden sret parameter. |
| 9270 | SmallVector<EVT, 1> PVTs; |
| 9271 | Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); |
| 9272 | |
| 9273 | ComputeValueVTs(*this, DL, PtrRetTy, PVTs); |
| 9274 | assert(PVTs.size() == 1 && "Pointers should fit in one register" ); |
| 9275 | EVT PtrVT = PVTs[0]; |
| 9276 | |
| 9277 | unsigned NumValues = RetTys.size(); |
| 9278 | ReturnValues.resize(NumValues); |
| 9279 | SmallVector<SDValue, 4> Chains(NumValues); |
| 9280 | |
| 9281 | // An aggregate return value cannot wrap around the address space, so |
| 9282 | // offsets to its parts don't wrap either. |
| 9283 | SDNodeFlags Flags; |
| 9284 | Flags.setNoUnsignedWrap(true); |
| 9285 | |
| 9286 | MachineFunction &MF = CLI.DAG.getMachineFunction(); |
| 9287 | unsigned HiddenSRetAlign = MF.getFrameInfo().getObjectAlignment(DemoteStackIdx); |
| 9288 | for (unsigned i = 0; i < NumValues; ++i) { |
| 9289 | SDValue Add = CLI.DAG.getPointerAdd(CLI.DL, DemoteStackSlot, Offsets[i], Flags); |
| 9290 | assert(DemoteStackSlot.getValueType() == PtrVT); |
| 9291 | SDValue L = CLI.DAG.getLoad( |
| 9292 | RetTys[i], CLI.DL, CLI.Chain, Add, |
| 9293 | MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), |
| 9294 | DemoteStackIdx, Offsets[i]), |
| 9295 | /* Alignment = */ MinAlign(HiddenSRetAlign, Offsets[i])); |
| 9296 | ReturnValues[i] = L; |
| 9297 | Chains[i] = L.getValue(1); |
| 9298 | } |
| 9299 | |
| 9300 | CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); |
| 9301 | } else { |
| 9302 | // Collect the legal value parts into potentially illegal values |
| 9303 | // that correspond to the original function's return values. |
| 9304 | Optional<ISD::NodeType> AssertOp; |
| 9305 | if (CLI.RetSExt) |
| 9306 | AssertOp = ISD::AssertSext; |
| 9307 | else if (CLI.RetZExt) |
| 9308 | AssertOp = ISD::AssertZext; |
| 9309 | unsigned CurReg = 0; |
| 9310 | for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { |
| 9311 | EVT VT = RetTys[I]; |
| 9312 | MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), |
| 9313 | CLI.CallConv, VT); |
| 9314 | unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), |
| 9315 | CLI.CallConv, VT); |
| 9316 | |
| 9317 | ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], |
| 9318 | NumRegs, RegisterVT, VT, nullptr, |
| 9319 | CLI.CallConv, AssertOp)); |
| 9320 | CurReg += NumRegs; |
| 9321 | } |
| 9322 | |
| 9323 | // For a function returning void, there is no return value. We can't create |
| 9324 | // such a node, so we just return a null return value in that case. In |
| 9325 | // that case, nothing will actually look at the value. |
| 9326 | if (ReturnValues.empty()) |
| 9327 | return std::make_pair(SDValue(), CLI.Chain); |
| 9328 | } |
| 9329 | |
| 9330 | SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, |
| 9331 | CLI.DAG.getVTList(RetTys), ReturnValues); |
| 9332 | return std::make_pair(Res, CLI.Chain); |
| 9333 | } |
| 9334 | |
| 9335 | void TargetLowering::LowerOperationWrapper(SDNode *N, |
| 9336 | SmallVectorImpl<SDValue> &Results, |
| 9337 | SelectionDAG &DAG) const { |
| 9338 | if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) |
| 9339 | Results.push_back(Res); |
| 9340 | } |
| 9341 | |
| 9342 | SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { |
| 9343 | llvm_unreachable("LowerOperation not implemented for this target!" ); |
| 9344 | } |
| 9345 | |
| 9346 | void |
| 9347 | SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { |
| 9348 | SDValue Op = getNonRegisterValue(V); |
| 9349 | assert((Op.getOpcode() != ISD::CopyFromReg || |
| 9350 | cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && |
| 9351 | "Copy from a reg to the same reg!" ); |
| 9352 | assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg" ); |
| 9353 | |
| 9354 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 9355 | // If this is an InlineAsm we have to match the registers required, not the |
| 9356 | // notional registers required by the type. |
| 9357 | |
| 9358 | RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), |
| 9359 | None); // This is not an ABI copy. |
| 9360 | SDValue Chain = DAG.getEntryNode(); |
| 9361 | |
| 9362 | ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == |
| 9363 | FuncInfo.PreferredExtendType.end()) |
| 9364 | ? ISD::ANY_EXTEND |
| 9365 | : FuncInfo.PreferredExtendType[V]; |
| 9366 | RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); |
| 9367 | PendingExports.push_back(Chain); |
| 9368 | } |
| 9369 | |
| 9370 | #include "llvm/CodeGen/SelectionDAGISel.h" |
| 9371 | |
| 9372 | /// isOnlyUsedInEntryBlock - If the specified argument is only used in the |
| 9373 | /// entry block, return true. This includes arguments used by switches, since |
| 9374 | /// the switch may expand into multiple basic blocks. |
| 9375 | static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { |
| 9376 | // With FastISel active, we may be splitting blocks, so force creation |
| 9377 | // of virtual registers for all non-dead arguments. |
| 9378 | if (FastISel) |
| 9379 | return A->use_empty(); |
| 9380 | |
| 9381 | const BasicBlock &Entry = A->getParent()->front(); |
| 9382 | for (const User *U : A->users()) |
| 9383 | if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) |
| 9384 | return false; // Use not in entry block. |
| 9385 | |
| 9386 | return true; |
| 9387 | } |
| 9388 | |
| 9389 | using ArgCopyElisionMapTy = |
| 9390 | DenseMap<const Argument *, |
| 9391 | std::pair<const AllocaInst *, const StoreInst *>>; |
| 9392 | |
| 9393 | /// Scan the entry block of the function in FuncInfo for arguments that look |
| 9394 | /// like copies into a local alloca. Record any copied arguments in |
| 9395 | /// ArgCopyElisionCandidates. |
| 9396 | static void |
| 9397 | findArgumentCopyElisionCandidates(const DataLayout &DL, |
| 9398 | FunctionLoweringInfo *FuncInfo, |
| 9399 | ArgCopyElisionMapTy &ArgCopyElisionCandidates) { |
| 9400 | // Record the state of every static alloca used in the entry block. Argument |
| 9401 | // allocas are all used in the entry block, so we need approximately as many |
| 9402 | // entries as we have arguments. |
| 9403 | enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; |
| 9404 | SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; |
| 9405 | unsigned NumArgs = FuncInfo->Fn->arg_size(); |
| 9406 | StaticAllocas.reserve(NumArgs * 2); |
| 9407 | |
| 9408 | auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { |
| 9409 | if (!V) |
| 9410 | return nullptr; |
| 9411 | V = V->stripPointerCasts(); |
| 9412 | const auto *AI = dyn_cast<AllocaInst>(V); |
| 9413 | if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) |
| 9414 | return nullptr; |
| 9415 | auto Iter = StaticAllocas.insert({AI, Unknown}); |
| 9416 | return &Iter.first->second; |
| 9417 | }; |
| 9418 | |
| 9419 | // Look for stores of arguments to static allocas. Look through bitcasts and |
| 9420 | // GEPs to handle type coercions, as long as the alloca is fully initialized |
| 9421 | // by the store. Any non-store use of an alloca escapes it and any subsequent |
| 9422 | // unanalyzed store might write it. |
| 9423 | // FIXME: Handle structs initialized with multiple stores. |
| 9424 | for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { |
| 9425 | // Look for stores, and handle non-store uses conservatively. |
| 9426 | const auto *SI = dyn_cast<StoreInst>(&I); |
| 9427 | if (!SI) { |
| 9428 | // We will look through cast uses, so ignore them completely. |
| 9429 | if (I.isCast()) |
| 9430 | continue; |
| 9431 | // Ignore debug info intrinsics, they don't escape or store to allocas. |
| 9432 | if (isa<DbgInfoIntrinsic>(I)) |
| 9433 | continue; |
| 9434 | // This is an unknown instruction. Assume it escapes or writes to all |
| 9435 | // static alloca operands. |
| 9436 | for (const Use &U : I.operands()) { |
| 9437 | if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) |
| 9438 | *Info = StaticAllocaInfo::Clobbered; |
| 9439 | } |
| 9440 | continue; |
| 9441 | } |
| 9442 | |
| 9443 | // If the stored value is a static alloca, mark it as escaped. |
| 9444 | if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) |
| 9445 | *Info = StaticAllocaInfo::Clobbered; |
| 9446 | |
| 9447 | // Check if the destination is a static alloca. |
| 9448 | const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); |
| 9449 | StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); |
| 9450 | if (!Info) |
| 9451 | continue; |
| 9452 | const AllocaInst *AI = cast<AllocaInst>(Dst); |
| 9453 | |
| 9454 | // Skip allocas that have been initialized or clobbered. |
| 9455 | if (*Info != StaticAllocaInfo::Unknown) |
| 9456 | continue; |
| 9457 | |
| 9458 | // Check if the stored value is an argument, and that this store fully |
| 9459 | // initializes the alloca. Don't elide copies from the same argument twice. |
| 9460 | const Value *Val = SI->getValueOperand()->stripPointerCasts(); |
| 9461 | const auto *Arg = dyn_cast<Argument>(Val); |
| 9462 | if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || |
| 9463 | Arg->getType()->isEmptyTy() || |
| 9464 | DL.getTypeStoreSize(Arg->getType()) != |
| 9465 | DL.getTypeAllocSize(AI->getAllocatedType()) || |
| 9466 | ArgCopyElisionCandidates.count(Arg)) { |
| 9467 | *Info = StaticAllocaInfo::Clobbered; |
| 9468 | continue; |
| 9469 | } |
| 9470 | |
| 9471 | LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI |
| 9472 | << '\n'); |
| 9473 | |
| 9474 | // Mark this alloca and store for argument copy elision. |
| 9475 | *Info = StaticAllocaInfo::Elidable; |
| 9476 | ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); |
| 9477 | |
| 9478 | // Stop scanning if we've seen all arguments. This will happen early in -O0 |
| 9479 | // builds, which is useful, because -O0 builds have large entry blocks and |
| 9480 | // many allocas. |
| 9481 | if (ArgCopyElisionCandidates.size() == NumArgs) |
| 9482 | break; |
| 9483 | } |
| 9484 | } |
| 9485 | |
| 9486 | /// Try to elide argument copies from memory into a local alloca. Succeeds if |
| 9487 | /// ArgVal is a load from a suitable fixed stack object. |
| 9488 | static void tryToElideArgumentCopy( |
| 9489 | FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, |
| 9490 | DenseMap<int, int> &ArgCopyElisionFrameIndexMap, |
| 9491 | SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, |
| 9492 | ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, |
| 9493 | SDValue ArgVal, bool &ArgHasUses) { |
| 9494 | // Check if this is a load from a fixed stack object. |
| 9495 | auto *LNode = dyn_cast<LoadSDNode>(ArgVal); |
| 9496 | if (!LNode) |
| 9497 | return; |
| 9498 | auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); |
| 9499 | if (!FINode) |
| 9500 | return; |
| 9501 | |
| 9502 | // Check that the fixed stack object is the right size and alignment. |
| 9503 | // Look at the alignment that the user wrote on the alloca instead of looking |
| 9504 | // at the stack object. |
| 9505 | auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); |
| 9506 | assert(ArgCopyIter != ArgCopyElisionCandidates.end()); |
| 9507 | const AllocaInst *AI = ArgCopyIter->second.first; |
| 9508 | int FixedIndex = FINode->getIndex(); |
| 9509 | int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; |
| 9510 | int OldIndex = AllocaIndex; |
| 9511 | MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); |
| 9512 | if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { |
| 9513 | LLVM_DEBUG( |
| 9514 | dbgs() << " argument copy elision failed due to bad fixed stack " |
| 9515 | "object size\n" ); |
| 9516 | return; |
| 9517 | } |
| 9518 | unsigned RequiredAlignment = AI->getAlignment(); |
| 9519 | if (!RequiredAlignment) { |
| 9520 | RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( |
| 9521 | AI->getAllocatedType()); |
| 9522 | } |
| 9523 | if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { |
| 9524 | LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " |
| 9525 | "greater than stack argument alignment (" |
| 9526 | << RequiredAlignment << " vs " |
| 9527 | << MFI.getObjectAlignment(FixedIndex) << ")\n" ); |
| 9528 | return; |
| 9529 | } |
| 9530 | |
| 9531 | // Perform the elision. Delete the old stack object and replace its only use |
| 9532 | // in the variable info map. Mark the stack object as mutable. |
| 9533 | LLVM_DEBUG({ |
| 9534 | dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' |
| 9535 | << " Replacing frame index " << OldIndex << " with " << FixedIndex |
| 9536 | << '\n'; |
| 9537 | }); |
| 9538 | MFI.RemoveStackObject(OldIndex); |
| 9539 | MFI.setIsImmutableObjectIndex(FixedIndex, false); |
| 9540 | AllocaIndex = FixedIndex; |
| 9541 | ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); |
| 9542 | Chains.push_back(ArgVal.getValue(1)); |
| 9543 | |
| 9544 | // Avoid emitting code for the store implementing the copy. |
| 9545 | const StoreInst *SI = ArgCopyIter->second.second; |
| 9546 | ElidedArgCopyInstrs.insert(SI); |
| 9547 | |
| 9548 | // Check for uses of the argument again so that we can avoid exporting ArgVal |
| 9549 | // if it is't used by anything other than the store. |
| 9550 | for (const Value *U : Arg.users()) { |
| 9551 | if (U != SI) { |
| 9552 | ArgHasUses = true; |
| 9553 | break; |
| 9554 | } |
| 9555 | } |
| 9556 | } |
| 9557 | |
| 9558 | void SelectionDAGISel::LowerArguments(const Function &F) { |
| 9559 | SelectionDAG &DAG = SDB->DAG; |
| 9560 | SDLoc dl = SDB->getCurSDLoc(); |
| 9561 | const DataLayout &DL = DAG.getDataLayout(); |
| 9562 | SmallVector<ISD::InputArg, 16> Ins; |
| 9563 | |
| 9564 | if (!FuncInfo->CanLowerReturn) { |
| 9565 | // Put in an sret pointer parameter before all the other parameters. |
| 9566 | SmallVector<EVT, 1> ValueVTs; |
| 9567 | ComputeValueVTs(*TLI, DAG.getDataLayout(), |
| 9568 | F.getReturnType()->getPointerTo( |
| 9569 | DAG.getDataLayout().getAllocaAddrSpace()), |
| 9570 | ValueVTs); |
| 9571 | |
| 9572 | // NOTE: Assuming that a pointer will never break down to more than one VT |
| 9573 | // or one register. |
| 9574 | ISD::ArgFlagsTy Flags; |
| 9575 | Flags.setSRet(); |
| 9576 | MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); |
| 9577 | ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, |
| 9578 | ISD::InputArg::NoArgIndex, 0); |
| 9579 | Ins.push_back(RetArg); |
| 9580 | } |
| 9581 | |
| 9582 | // Look for stores of arguments to static allocas. Mark such arguments with a |
| 9583 | // flag to ask the target to give us the memory location of that argument if |
| 9584 | // available. |
| 9585 | ArgCopyElisionMapTy ArgCopyElisionCandidates; |
| 9586 | findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); |
| 9587 | |
| 9588 | // Set up the incoming argument description vector. |
| 9589 | for (const Argument &Arg : F.args()) { |
| 9590 | unsigned ArgNo = Arg.getArgNo(); |
| 9591 | SmallVector<EVT, 4> ValueVTs; |
| 9592 | ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); |
| 9593 | bool isArgValueUsed = !Arg.use_empty(); |
| 9594 | unsigned PartBase = 0; |
| 9595 | Type *FinalType = Arg.getType(); |
| 9596 | |
| 9597 | // Ignore byval attribute on CHERI capability arguments because we just |
| 9598 | // pass them in capability registers |
| 9599 | bool isArgCHERICapability = isCheriPointer(FinalType, &DAG.getDataLayout()); |
| 9600 | if (Arg.hasAttribute(Attribute::ByVal) && !isArgCHERICapability) |
| 9601 | FinalType = cast<PointerType>(FinalType)->getElementType(); |
| 9602 | bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( |
| 9603 | FinalType, F.getCallingConv(), F.isVarArg()); |
| 9604 | for (unsigned Value = 0, NumValues = ValueVTs.size(); |
| 9605 | Value != NumValues; ++Value) { |
| 9606 | EVT VT = ValueVTs[Value]; |
| 9607 | Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); |
| 9608 | ISD::ArgFlagsTy Flags; |
| 9609 | |
| 9610 | // Certain targets (such as MIPS), may have a different ABI alignment |
| 9611 | // for a type depending on the context. Give the target a chance to |
| 9612 | // specify the alignment it wants. |
| 9613 | unsigned OriginalAlignment = |
| 9614 | TLI->getABIAlignmentForCallingConv(ArgTy, DL); |
| 9615 | |
| 9616 | if (Arg.getType()->isPointerTy()) { |
| 9617 | Flags.setPointer(); |
| 9618 | Flags.setPointerAddrSpace( |
| 9619 | cast<PointerType>(Arg.getType())->getAddressSpace()); |
| 9620 | } |
| 9621 | if (Arg.hasAttribute(Attribute::ZExt)) |
| 9622 | Flags.setZExt(); |
| 9623 | if (Arg.hasAttribute(Attribute::SExt)) |
| 9624 | Flags.setSExt(); |
| 9625 | if (Arg.hasAttribute(Attribute::InReg)) { |
| 9626 | // If we are using vectorcall calling convention, a structure that is |
| 9627 | // passed InReg - is surely an HVA |
| 9628 | if (F.getCallingConv() == CallingConv::X86_VectorCall && |
| 9629 | isa<StructType>(Arg.getType())) { |
| 9630 | // The first value of a structure is marked |
| 9631 | if (0 == Value) |
| 9632 | Flags.setHvaStart(); |
| 9633 | Flags.setHva(); |
| 9634 | } |
| 9635 | // Set InReg Flag |
| 9636 | Flags.setInReg(); |
| 9637 | } |
| 9638 | if (Arg.hasAttribute(Attribute::StructRet)) |
| 9639 | Flags.setSRet(); |
| 9640 | if (Arg.hasAttribute(Attribute::SwiftSelf)) |
| 9641 | Flags.setSwiftSelf(); |
| 9642 | if (Arg.hasAttribute(Attribute::SwiftError)) |
| 9643 | Flags.setSwiftError(); |
| 9644 | if (Arg.hasAttribute(Attribute::ByVal) && !isArgCHERICapability) |
| 9645 | Flags.setByVal(); |
| 9646 | if (Arg.hasAttribute(Attribute::InAlloca)) { |
| 9647 | Flags.setInAlloca(); |
| 9648 | // Set the byval flag for CCAssignFn callbacks that don't know about |
| 9649 | // inalloca. This way we can know how many bytes we should've allocated |
| 9650 | // and how many bytes a callee cleanup function will pop. If we port |
| 9651 | // inalloca to more targets, we'll have to add custom inalloca handling |
| 9652 | // in the various CC lowering callbacks. |
| 9653 | Flags.setByVal(); |
| 9654 | } |
| 9655 | if (F.getCallingConv() == CallingConv::X86_INTR) { |
| 9656 | // IA Interrupt passes frame (1st parameter) by value in the stack. |
| 9657 | if (ArgNo == 0) |
| 9658 | Flags.setByVal(); |
| 9659 | } |
| 9660 | if (Flags.isByVal() || Flags.isInAlloca()) { |
| 9661 | PointerType *Ty = cast<PointerType>(Arg.getType()); |
| 9662 | Type *ElementTy = Ty->getElementType(); |
| 9663 | |
| 9664 | // For ByVal, size and alignment should be passed from FE. BE will |
| 9665 | // guess if this info is not there but there are cases it cannot get |
| 9666 | // right. |
| 9667 | unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); |
| 9668 | Flags.setByValSize(FrameSize); |
| 9669 | |
| 9670 | unsigned FrameAlign; |
| 9671 | if (Arg.getParamAlignment()) |
| 9672 | FrameAlign = Arg.getParamAlignment(); |
| 9673 | else |
| 9674 | FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); |
| 9675 | Flags.setByValAlign(FrameAlign); |
| 9676 | } |
| 9677 | if (Arg.hasAttribute(Attribute::Nest)) |
| 9678 | Flags.setNest(); |
| 9679 | if (NeedsRegBlock) |
| 9680 | Flags.setInConsecutiveRegs(); |
| 9681 | Flags.setOrigAlign(OriginalAlignment); |
| 9682 | if (ArgCopyElisionCandidates.count(&Arg)) |
| 9683 | Flags.setCopyElisionCandidate(); |
| 9684 | |
| 9685 | MVT RegisterVT = TLI->getRegisterTypeForCallingConv( |
| 9686 | *CurDAG->getContext(), F.getCallingConv(), VT); |
| 9687 | unsigned NumRegs = TLI->getNumRegistersForCallingConv( |
| 9688 | *CurDAG->getContext(), F.getCallingConv(), VT); |
| 9689 | for (unsigned i = 0; i != NumRegs; ++i) { |
| 9690 | ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, |
| 9691 | ArgNo, PartBase+i*RegisterVT.getStoreSize()); |
| 9692 | if (NumRegs > 1 && i == 0) |
| 9693 | MyFlags.Flags.setSplit(); |
| 9694 | // if it isn't first piece, alignment must be 1 |
| 9695 | else if (i > 0) { |
| 9696 | MyFlags.Flags.setOrigAlign(1); |
| 9697 | if (i == NumRegs - 1) |
| 9698 | MyFlags.Flags.setSplitEnd(); |
| 9699 | } |
| 9700 | Ins.push_back(MyFlags); |
| 9701 | } |
| 9702 | if (NeedsRegBlock && Value == NumValues - 1) |
| 9703 | Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); |
| 9704 | PartBase += VT.getStoreSize(); |
| 9705 | } |
| 9706 | } |
| 9707 | |
| 9708 | // Call the target to set up the argument values. |
| 9709 | SmallVector<SDValue, 8> InVals; |
| 9710 | SDValue NewRoot = TLI->LowerFormalArguments( |
| 9711 | DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); |
| 9712 | |
| 9713 | // Verify that the target's LowerFormalArguments behaved as expected. |
| 9714 | assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && |
| 9715 | "LowerFormalArguments didn't return a valid chain!" ); |
| 9716 | assert(InVals.size() == Ins.size() && |
| 9717 | "LowerFormalArguments didn't emit the correct number of values!" ); |
| 9718 | LLVM_DEBUG({ |
| 9719 | for (unsigned i = 0, e = Ins.size(); i != e; ++i) { |
| 9720 | assert(InVals[i].getNode() && |
| 9721 | "LowerFormalArguments emitted a null value!" ); |
| 9722 | assert(EVT(Ins[i].VT) == InVals[i].getValueType() && |
| 9723 | "LowerFormalArguments emitted a value with the wrong type!" ); |
| 9724 | } |
| 9725 | }); |
| 9726 | |
| 9727 | // Update the DAG with the new chain value resulting from argument lowering. |
| 9728 | DAG.setRoot(NewRoot); |
| 9729 | |
| 9730 | // Set up the argument values. |
| 9731 | unsigned i = 0; |
| 9732 | if (!FuncInfo->CanLowerReturn) { |
| 9733 | // Create a virtual register for the sret pointer, and put in a copy |
| 9734 | // from the sret argument into it. |
| 9735 | SmallVector<EVT, 1> ValueVTs; |
| 9736 | ComputeValueVTs(*TLI, DAG.getDataLayout(), |
| 9737 | F.getReturnType()->getPointerTo( |
| 9738 | DAG.getDataLayout().getAllocaAddrSpace()), |
| 9739 | ValueVTs); |
| 9740 | MVT VT = ValueVTs[0].getSimpleVT(); |
| 9741 | MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); |
| 9742 | Optional<ISD::NodeType> AssertOp = None; |
| 9743 | SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, |
| 9744 | nullptr, F.getCallingConv(), AssertOp); |
| 9745 | |
| 9746 | MachineFunction& MF = SDB->DAG.getMachineFunction(); |
| 9747 | MachineRegisterInfo& RegInfo = MF.getRegInfo(); |
| 9748 | unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); |
| 9749 | FuncInfo->DemoteRegister = SRetReg; |
| 9750 | NewRoot = |
| 9751 | SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); |
| 9752 | DAG.setRoot(NewRoot); |
| 9753 | |
| 9754 | // i indexes lowered arguments. Bump it past the hidden sret argument. |
| 9755 | ++i; |
| 9756 | } |
| 9757 | |
| 9758 | SmallVector<SDValue, 4> Chains; |
| 9759 | DenseMap<int, int> ArgCopyElisionFrameIndexMap; |
| 9760 | for (const Argument &Arg : F.args()) { |
| 9761 | SmallVector<SDValue, 4> ArgValues; |
| 9762 | SmallVector<EVT, 4> ValueVTs; |
| 9763 | ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); |
| 9764 | unsigned NumValues = ValueVTs.size(); |
| 9765 | if (NumValues == 0) |
| 9766 | continue; |
| 9767 | |
| 9768 | bool ArgHasUses = !Arg.use_empty(); |
| 9769 | |
| 9770 | // Elide the copying store if the target loaded this argument from a |
| 9771 | // suitable fixed stack object. |
| 9772 | if (Ins[i].Flags.isCopyElisionCandidate()) { |
| 9773 | tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, |
| 9774 | ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, |
| 9775 | InVals[i], ArgHasUses); |
| 9776 | } |
| 9777 | |
| 9778 | // If this argument is unused then remember its value. It is used to generate |
| 9779 | // debugging information. |
| 9780 | bool isSwiftErrorArg = |
| 9781 | TLI->supportSwiftError() && |
| 9782 | Arg.hasAttribute(Attribute::SwiftError); |
| 9783 | if (!ArgHasUses && !isSwiftErrorArg) { |
| 9784 | SDB->setUnusedArgValue(&Arg, InVals[i]); |
| 9785 | |
| 9786 | // Also remember any frame index for use in FastISel. |
| 9787 | if (FrameIndexSDNode *FI = |
| 9788 | dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) |
| 9789 | FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); |
| 9790 | } |
| 9791 | |
| 9792 | for (unsigned Val = 0; Val != NumValues; ++Val) { |
| 9793 | EVT VT = ValueVTs[Val]; |
| 9794 | MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), |
| 9795 | F.getCallingConv(), VT); |
| 9796 | unsigned NumParts = TLI->getNumRegistersForCallingConv( |
| 9797 | *CurDAG->getContext(), F.getCallingConv(), VT); |
| 9798 | |
| 9799 | // Even an apparant 'unused' swifterror argument needs to be returned. So |
| 9800 | // we do generate a copy for it that can be used on return from the |
| 9801 | // function. |
| 9802 | if (ArgHasUses || isSwiftErrorArg) { |
| 9803 | Optional<ISD::NodeType> AssertOp; |
| 9804 | if (Arg.hasAttribute(Attribute::SExt)) |
| 9805 | AssertOp = ISD::AssertSext; |
| 9806 | else if (Arg.hasAttribute(Attribute::ZExt)) |
| 9807 | AssertOp = ISD::AssertZext; |
| 9808 | |
| 9809 | ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, |
| 9810 | PartVT, VT, nullptr, |
| 9811 | F.getCallingConv(), AssertOp)); |
| 9812 | } |
| 9813 | |
| 9814 | i += NumParts; |
| 9815 | } |
| 9816 | |
| 9817 | // We don't need to do anything else for unused arguments. |
| 9818 | if (ArgValues.empty()) |
| 9819 | continue; |
| 9820 | |
| 9821 | // Note down frame index. |
| 9822 | if (FrameIndexSDNode *FI = |
| 9823 | dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) |
| 9824 | FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); |
| 9825 | |
| 9826 | SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), |
| 9827 | SDB->getCurSDLoc()); |
| 9828 | |
| 9829 | SDB->setValue(&Arg, Res); |
| 9830 | if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { |
| 9831 | // We want to associate the argument with the frame index, among |
| 9832 | // involved operands, that correspond to the lowest address. The |
| 9833 | // getCopyFromParts function, called earlier, is swapping the order of |
| 9834 | // the operands to BUILD_PAIR depending on endianness. The result of |
| 9835 | // that swapping is that the least significant bits of the argument will |
| 9836 | // be in the first operand of the BUILD_PAIR node, and the most |
| 9837 | // significant bits will be in the second operand. |
| 9838 | unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; |
| 9839 | if (LoadSDNode *LNode = |
| 9840 | dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) |
| 9841 | if (FrameIndexSDNode *FI = |
| 9842 | dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) |
| 9843 | FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); |
| 9844 | } |
| 9845 | |
| 9846 | // Update the SwiftErrorVRegDefMap. |
| 9847 | if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { |
| 9848 | unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); |
| 9849 | if (TargetRegisterInfo::isVirtualRegister(Reg)) |
| 9850 | SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), |
| 9851 | Reg); |
| 9852 | } |
| 9853 | |
| 9854 | // If this argument is live outside of the entry block, insert a copy from |
| 9855 | // wherever we got it to the vreg that other BB's will reference it as. |
| 9856 | if (Res.getOpcode() == ISD::CopyFromReg) { |
| 9857 | // If we can, though, try to skip creating an unnecessary vreg. |
| 9858 | // FIXME: This isn't very clean... it would be nice to make this more |
| 9859 | // general. |
| 9860 | unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); |
| 9861 | if (TargetRegisterInfo::isVirtualRegister(Reg)) { |
| 9862 | FuncInfo->ValueMap[&Arg] = Reg; |
| 9863 | continue; |
| 9864 | } |
| 9865 | } |
| 9866 | if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { |
| 9867 | FuncInfo->InitializeRegForValue(&Arg); |
| 9868 | SDB->CopyToExportRegsIfNeeded(&Arg); |
| 9869 | } |
| 9870 | } |
| 9871 | |
| 9872 | if (!Chains.empty()) { |
| 9873 | Chains.push_back(NewRoot); |
| 9874 | NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); |
| 9875 | } |
| 9876 | |
| 9877 | DAG.setRoot(NewRoot); |
| 9878 | |
| 9879 | assert(i == InVals.size() && "Argument register count mismatch!" ); |
| 9880 | |
| 9881 | // If any argument copy elisions occurred and we have debug info, update the |
| 9882 | // stale frame indices used in the dbg.declare variable info table. |
| 9883 | MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); |
| 9884 | if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { |
| 9885 | for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { |
| 9886 | auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); |
| 9887 | if (I != ArgCopyElisionFrameIndexMap.end()) |
| 9888 | VI.Slot = I->second; |
| 9889 | } |
| 9890 | } |
| 9891 | |
| 9892 | // Finally, if the target has anything special to do, allow it to do so. |
| 9893 | EmitFunctionEntryCode(); |
| 9894 | } |
| 9895 | |
| 9896 | /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to |
| 9897 | /// ensure constants are generated when needed. Remember the virtual registers |
| 9898 | /// that need to be added to the Machine PHI nodes as input. We cannot just |
| 9899 | /// directly add them, because expansion might result in multiple MBB's for one |
| 9900 | /// BB. As such, the start of the BB might correspond to a different MBB than |
| 9901 | /// the end. |
| 9902 | void |
| 9903 | SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { |
| 9904 | const Instruction *TI = LLVMBB->getTerminator(); |
| 9905 | |
| 9906 | SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; |
| 9907 | |
| 9908 | // Check PHI nodes in successors that expect a value to be available from this |
| 9909 | // block. |
| 9910 | for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { |
| 9911 | const BasicBlock *SuccBB = TI->getSuccessor(succ); |
| 9912 | if (!isa<PHINode>(SuccBB->begin())) continue; |
| 9913 | MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; |
| 9914 | |
| 9915 | // If this terminator has multiple identical successors (common for |
| 9916 | // switches), only handle each succ once. |
| 9917 | if (!SuccsHandled.insert(SuccMBB).second) |
| 9918 | continue; |
| 9919 | |
| 9920 | MachineBasicBlock::iterator MBBI = SuccMBB->begin(); |
| 9921 | |
| 9922 | // At this point we know that there is a 1-1 correspondence between LLVM PHI |
| 9923 | // nodes and Machine PHI nodes, but the incoming operands have not been |
| 9924 | // emitted yet. |
| 9925 | for (const PHINode &PN : SuccBB->phis()) { |
| 9926 | // Ignore dead phi's. |
| 9927 | if (PN.use_empty()) |
| 9928 | continue; |
| 9929 | |
| 9930 | // Skip empty types |
| 9931 | if (PN.getType()->isEmptyTy()) |
| 9932 | continue; |
| 9933 | |
| 9934 | unsigned Reg; |
| 9935 | const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); |
| 9936 | |
| 9937 | if (const Constant *C = dyn_cast<Constant>(PHIOp)) { |
| 9938 | unsigned &RegOut = ConstantsOut[C]; |
| 9939 | if (RegOut == 0) { |
| 9940 | RegOut = FuncInfo.CreateRegs(C); |
| 9941 | CopyValueToVirtualRegister(C, RegOut); |
| 9942 | } |
| 9943 | Reg = RegOut; |
| 9944 | } else { |
| 9945 | DenseMap<const Value *, unsigned>::iterator I = |
| 9946 | FuncInfo.ValueMap.find(PHIOp); |
| 9947 | if (I != FuncInfo.ValueMap.end()) |
| 9948 | Reg = I->second; |
| 9949 | else { |
| 9950 | assert(isa<AllocaInst>(PHIOp) && |
| 9951 | FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && |
| 9952 | "Didn't codegen value into a register!??" ); |
| 9953 | Reg = FuncInfo.CreateRegs(PHIOp); |
| 9954 | CopyValueToVirtualRegister(PHIOp, Reg); |
| 9955 | } |
| 9956 | } |
| 9957 | |
| 9958 | // Remember that this register needs to added to the machine PHI node as |
| 9959 | // the input for this MBB. |
| 9960 | SmallVector<EVT, 4> ValueVTs; |
| 9961 | const TargetLowering &TLI = DAG.getTargetLoweringInfo(); |
| 9962 | ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); |
| 9963 | for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { |
| 9964 | EVT VT = ValueVTs[vti]; |
| 9965 | unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); |
| 9966 | for (unsigned i = 0, e = NumRegisters; i != e; ++i) |
| 9967 | FuncInfo.PHINodesToUpdate.push_back( |
| 9968 | std::make_pair(&*MBBI++, Reg + i)); |
| 9969 | Reg += NumRegisters; |
| 9970 | } |
| 9971 | } |
| 9972 | } |
| 9973 | |
| 9974 | ConstantsOut.clear(); |
| 9975 | } |
| 9976 | |
| 9977 | /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB |
| 9978 | /// is 0. |
| 9979 | MachineBasicBlock * |
| 9980 | SelectionDAGBuilder::StackProtectorDescriptor:: |
| 9981 | AddSuccessorMBB(const BasicBlock *BB, |
| 9982 | MachineBasicBlock *ParentMBB, |
| 9983 | bool IsLikely, |
| 9984 | MachineBasicBlock *SuccMBB) { |
| 9985 | // If SuccBB has not been created yet, create it. |
| 9986 | if (!SuccMBB) { |
| 9987 | MachineFunction *MF = ParentMBB->getParent(); |
| 9988 | MachineFunction::iterator BBI(ParentMBB); |
| 9989 | SuccMBB = MF->CreateMachineBasicBlock(BB); |
| 9990 | MF->insert(++BBI, SuccMBB); |
| 9991 | } |
| 9992 | // Add it as a successor of ParentMBB. |
| 9993 | ParentMBB->addSuccessor( |
| 9994 | SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); |
| 9995 | return SuccMBB; |
| 9996 | } |
| 9997 | |
| 9998 | MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { |
| 9999 | MachineFunction::iterator I(MBB); |
| 10000 | if (++I == FuncInfo.MF->end()) |
| 10001 | return nullptr; |
| 10002 | return &*I; |
| 10003 | } |
| 10004 | |
| 10005 | /// During lowering new call nodes can be created (such as memset, etc.). |
| 10006 | /// Those will become new roots of the current DAG, but complications arise |
| 10007 | /// when they are tail calls. In such cases, the call lowering will update |
| 10008 | /// the root, but the builder still needs to know that a tail call has been |
| 10009 | /// lowered in order to avoid generating an additional return. |
| 10010 | void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { |
| 10011 | // If the node is null, we do have a tail call. |
| 10012 | if (MaybeTC.getNode() != nullptr) |
| 10013 | DAG.setRoot(MaybeTC); |
| 10014 | else |
| 10015 | HasTailCall = true; |
| 10016 | } |
| 10017 | |
| 10018 | void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, |
| 10019 | MachineBasicBlock *SwitchMBB, |
| 10020 | MachineBasicBlock *DefaultMBB) { |
| 10021 | MachineFunction *CurMF = FuncInfo.MF; |
| 10022 | MachineBasicBlock *NextMBB = nullptr; |
| 10023 | MachineFunction::iterator BBI(W.MBB); |
| 10024 | if (++BBI != FuncInfo.MF->end()) |
| 10025 | NextMBB = &*BBI; |
| 10026 | |
| 10027 | unsigned Size = W.LastCluster - W.FirstCluster + 1; |
| 10028 | |
| 10029 | BranchProbabilityInfo *BPI = FuncInfo.BPI; |
| 10030 | |
| 10031 | if (Size == 2 && W.MBB == SwitchMBB) { |
| 10032 | // If any two of the cases has the same destination, and if one value |
| 10033 | // is the same as the other, but has one bit unset that the other has set, |
| 10034 | // use bit manipulation to do two compares at once. For example: |
| 10035 | // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" |
| 10036 | // TODO: This could be extended to merge any 2 cases in switches with 3 |
| 10037 | // cases. |
| 10038 | // TODO: Handle cases where W.CaseBB != SwitchBB. |
| 10039 | CaseCluster &Small = *W.FirstCluster; |
| 10040 | CaseCluster &Big = *W.LastCluster; |
| 10041 | |
| 10042 | if (Small.Low == Small.High && Big.Low == Big.High && |
| 10043 | Small.MBB == Big.MBB) { |
| 10044 | const APInt &SmallValue = Small.Low->getValue(); |
| 10045 | const APInt &BigValue = Big.Low->getValue(); |
| 10046 | |
| 10047 | // Check that there is only one bit different. |
| 10048 | APInt CommonBit = BigValue ^ SmallValue; |
| 10049 | if (CommonBit.isPowerOf2()) { |
| 10050 | SDValue CondLHS = getValue(Cond); |
| 10051 | EVT VT = CondLHS.getValueType(); |
| 10052 | SDLoc DL = getCurSDLoc(); |
| 10053 | |
| 10054 | SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, |
| 10055 | DAG.getConstant(CommonBit, DL, VT)); |
| 10056 | SDValue Cond = DAG.getSetCC( |
| 10057 | DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), |
| 10058 | ISD::SETEQ); |
| 10059 | |
| 10060 | // Update successor info. |
| 10061 | // Both Small and Big will jump to Small.BB, so we sum up the |
| 10062 | // probabilities. |
| 10063 | addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); |
| 10064 | if (BPI) |
| 10065 | addSuccessorWithProb( |
| 10066 | SwitchMBB, DefaultMBB, |
| 10067 | // The default destination is the first successor in IR. |
| 10068 | BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); |
| 10069 | else |
| 10070 | addSuccessorWithProb(SwitchMBB, DefaultMBB); |
| 10071 | |
| 10072 | // Insert the true branch. |
| 10073 | SDValue BrCond = |
| 10074 | DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, |
| 10075 | DAG.getBasicBlock(Small.MBB)); |
| 10076 | // Insert the false branch. |
| 10077 | BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, |
| 10078 | DAG.getBasicBlock(DefaultMBB)); |
| 10079 | |
| 10080 | DAG.setRoot(BrCond); |
| 10081 | return; |
| 10082 | } |
| 10083 | } |
| 10084 | } |
| 10085 | |
| 10086 | if (TM.getOptLevel() != CodeGenOpt::None) { |
| 10087 | // Here, we order cases by probability so the most likely case will be |
| 10088 | // checked first. However, two clusters can have the same probability in |
| 10089 | // which case their relative ordering is non-deterministic. So we use Low |
| 10090 | // as a tie-breaker as clusters are guaranteed to never overlap. |
| 10091 | llvm::sort(W.FirstCluster, W.LastCluster + 1, |
| 10092 | [](const CaseCluster &a, const CaseCluster &b) { |
| 10093 | return a.Prob != b.Prob ? |
| 10094 | a.Prob > b.Prob : |
| 10095 | a.Low->getValue().slt(b.Low->getValue()); |
| 10096 | }); |
| 10097 | |
| 10098 | // Rearrange the case blocks so that the last one falls through if possible |
| 10099 | // without changing the order of probabilities. |
| 10100 | for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { |
| 10101 | --I; |
| 10102 | if (I->Prob > W.LastCluster->Prob) |
| 10103 | break; |
| 10104 | if (I->Kind == CC_Range && I->MBB == NextMBB) { |
| 10105 | std::swap(*I, *W.LastCluster); |
| 10106 | break; |
| 10107 | } |
| 10108 | } |
| 10109 | } |
| 10110 | |
| 10111 | // Compute total probability. |
| 10112 | BranchProbability DefaultProb = W.DefaultProb; |
| 10113 | BranchProbability UnhandledProbs = DefaultProb; |
| 10114 | for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) |
| 10115 | UnhandledProbs += I->Prob; |
| 10116 | |
| 10117 | MachineBasicBlock *CurMBB = W.MBB; |
| 10118 | for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { |
| 10119 | bool FallthroughUnreachable = false; |
| 10120 | MachineBasicBlock *Fallthrough; |
| 10121 | if (I == W.LastCluster) { |
| 10122 | // For the last cluster, fall through to the default destination. |
| 10123 | Fallthrough = DefaultMBB; |
| 10124 | FallthroughUnreachable = isa<UnreachableInst>( |
| 10125 | DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); |
| 10126 | } else { |
| 10127 | Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); |
| 10128 | CurMF->insert(BBI, Fallthrough); |
| 10129 | // Put Cond in a virtual register to make it available from the new blocks. |
| 10130 | ExportFromCurrentBlock(Cond); |
| 10131 | } |
| 10132 | UnhandledProbs -= I->Prob; |
| 10133 | |
| 10134 | switch (I->Kind) { |
| 10135 | case CC_JumpTable: { |
| 10136 | // FIXME: Optimize away range check based on pivot comparisons. |
| 10137 | JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; |
| 10138 | SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; |
| 10139 | |
| 10140 | // The jump block hasn't been inserted yet; insert it here. |
| 10141 | MachineBasicBlock *JumpMBB = JT->MBB; |
| 10142 | CurMF->insert(BBI, JumpMBB); |
| 10143 | |
| 10144 | auto JumpProb = I->Prob; |
| 10145 | auto FallthroughProb = UnhandledProbs; |
| 10146 | |
| 10147 | // If the default statement is a target of the jump table, we evenly |
| 10148 | // distribute the default probability to successors of CurMBB. Also |
| 10149 | // update the probability on the edge from JumpMBB to Fallthrough. |
| 10150 | for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), |
| 10151 | SE = JumpMBB->succ_end(); |
| 10152 | SI != SE; ++SI) { |
| 10153 | if (*SI == DefaultMBB) { |
| 10154 | JumpProb += DefaultProb / 2; |
| 10155 | FallthroughProb -= DefaultProb / 2; |
| 10156 | JumpMBB->setSuccProbability(SI, DefaultProb / 2); |
| 10157 | JumpMBB->normalizeSuccProbs(); |
| 10158 | break; |
| 10159 | } |
| 10160 | } |
| 10161 | |
| 10162 | if (FallthroughUnreachable) { |
| 10163 | // Skip the range check if the fallthrough block is unreachable. |
| 10164 | JTH->OmitRangeCheck = true; |
| 10165 | } |
| 10166 | |
| 10167 | if (!JTH->OmitRangeCheck) |
| 10168 | addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); |
| 10169 | addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); |
| 10170 | CurMBB->normalizeSuccProbs(); |
| 10171 | |
| 10172 | // The jump table header will be inserted in our current block, do the |
| 10173 | // range check, and fall through to our fallthrough block. |
| 10174 | JTH->HeaderBB = CurMBB; |
| 10175 | JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. |
| 10176 | |
| 10177 | // If we're in the right place, emit the jump table header right now. |
| 10178 | if (CurMBB == SwitchMBB) { |
| 10179 | visitJumpTableHeader(*JT, *JTH, SwitchMBB); |
| 10180 | JTH->Emitted = true; |
| 10181 | } |
| 10182 | break; |
| 10183 | } |
| 10184 | case CC_BitTests: { |
| 10185 | // FIXME: If Fallthrough is unreachable, skip the range check. |
| 10186 | |
| 10187 | // FIXME: Optimize away range check based on pivot comparisons. |
| 10188 | BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; |
| 10189 | |
| 10190 | // The bit test blocks haven't been inserted yet; insert them here. |
| 10191 | for (BitTestCase &BTC : BTB->Cases) |
| 10192 | CurMF->insert(BBI, BTC.ThisBB); |
| 10193 | |
| 10194 | // Fill in fields of the BitTestBlock. |
| 10195 | BTB->Parent = CurMBB; |
| 10196 | BTB->Default = Fallthrough; |
| 10197 | |
| 10198 | BTB->DefaultProb = UnhandledProbs; |
| 10199 | // If the cases in bit test don't form a contiguous range, we evenly |
| 10200 | // distribute the probability on the edge to Fallthrough to two |
| 10201 | // successors of CurMBB. |
| 10202 | if (!BTB->ContiguousRange) { |
| 10203 | BTB->Prob += DefaultProb / 2; |
| 10204 | BTB->DefaultProb -= DefaultProb / 2; |
| 10205 | } |
| 10206 | |
| 10207 | // If we're in the right place, emit the bit test header right now. |
| 10208 | if (CurMBB == SwitchMBB) { |
| 10209 | visitBitTestHeader(*BTB, SwitchMBB); |
| 10210 | BTB->Emitted = true; |
| 10211 | } |
| 10212 | break; |
| 10213 | } |
| 10214 | case CC_Range: { |
| 10215 | const Value *RHS, *LHS, *MHS; |
| 10216 | ISD::CondCode CC; |
| 10217 | if (I->Low == I->High) { |
| 10218 | // Check Cond == I->Low. |
| 10219 | CC = ISD::SETEQ; |
| 10220 | LHS = Cond; |
| 10221 | RHS=I->Low; |
| 10222 | MHS = nullptr; |
| 10223 | } else { |
| 10224 | // Check I->Low <= Cond <= I->High. |
| 10225 | CC = ISD::SETLE; |
| 10226 | LHS = I->Low; |
| 10227 | MHS = Cond; |
| 10228 | RHS = I->High; |
| 10229 | } |
| 10230 | |
| 10231 | // If Fallthrough is unreachable, fold away the comparison. |
| 10232 | if (FallthroughUnreachable) |
| 10233 | CC = ISD::SETTRUE; |
| 10234 | |
| 10235 | // The false probability is the sum of all unhandled cases. |
| 10236 | CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, |
| 10237 | getCurSDLoc(), I->Prob, UnhandledProbs); |
| 10238 | |
| 10239 | if (CurMBB == SwitchMBB) |
| 10240 | visitSwitchCase(CB, SwitchMBB); |
| 10241 | else |
| 10242 | SL->SwitchCases.push_back(CB); |
| 10243 | |
| 10244 | break; |
| 10245 | } |
| 10246 | } |
| 10247 | CurMBB = Fallthrough; |
| 10248 | } |
| 10249 | } |
| 10250 | |
| 10251 | unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, |
| 10252 | CaseClusterIt First, |
| 10253 | CaseClusterIt Last) { |
| 10254 | return std::count_if(First, Last + 1, [&](const CaseCluster &X) { |
| 10255 | if (X.Prob != CC.Prob) |
| 10256 | return X.Prob > CC.Prob; |
| 10257 | |
| 10258 | // Ties are broken by comparing the case value. |
| 10259 | return X.Low->getValue().slt(CC.Low->getValue()); |
| 10260 | }); |
| 10261 | } |
| 10262 | |
| 10263 | void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, |
| 10264 | const SwitchWorkListItem &W, |
| 10265 | Value *Cond, |
| 10266 | MachineBasicBlock *SwitchMBB) { |
| 10267 | assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && |
| 10268 | "Clusters not sorted?" ); |
| 10269 | |
| 10270 | assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!" ); |
| 10271 | |
| 10272 | // Balance the tree based on branch probabilities to create a near-optimal (in |
| 10273 | // terms of search time given key frequency) binary search tree. See e.g. Kurt |
| 10274 | // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). |
| 10275 | CaseClusterIt LastLeft = W.FirstCluster; |
| 10276 | CaseClusterIt FirstRight = W.LastCluster; |
| 10277 | auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; |
| 10278 | auto RightProb = FirstRight->Prob + W.DefaultProb / 2; |
| 10279 | |
| 10280 | // Move LastLeft and FirstRight towards each other from opposite directions to |
| 10281 | // find a partitioning of the clusters which balances the probability on both |
| 10282 | // sides. If LeftProb and RightProb are equal, alternate which side is |
| 10283 | // taken to ensure 0-probability nodes are distributed evenly. |
| 10284 | unsigned I = 0; |
| 10285 | while (LastLeft + 1 < FirstRight) { |
| 10286 | if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) |
| 10287 | LeftProb += (++LastLeft)->Prob; |
| 10288 | else |
| 10289 | RightProb += (--FirstRight)->Prob; |
| 10290 | I++; |
| 10291 | } |
| 10292 | |
| 10293 | while (true) { |
| 10294 | // Our binary search tree differs from a typical BST in that ours can have up |
| 10295 | // to three values in each leaf. The pivot selection above doesn't take that |
| 10296 | // into account, which means the tree might require more nodes and be less |
| 10297 | // efficient. We compensate for this here. |
| 10298 | |
| 10299 | unsigned NumLeft = LastLeft - W.FirstCluster + 1; |
| 10300 | unsigned NumRight = W.LastCluster - FirstRight + 1; |
| 10301 | |
| 10302 | if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { |
| 10303 | // If one side has less than 3 clusters, and the other has more than 3, |
| 10304 | // consider taking a cluster from the other side. |
| 10305 | |
| 10306 | if (NumLeft < NumRight) { |
| 10307 | // Consider moving the first cluster on the right to the left side. |
| 10308 | CaseCluster &CC = *FirstRight; |
| 10309 | unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); |
| 10310 | unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); |
| 10311 | if (LeftSideRank <= RightSideRank) { |
| 10312 | // Moving the cluster to the left does not demote it. |
| 10313 | ++LastLeft; |
| 10314 | ++FirstRight; |
| 10315 | continue; |
| 10316 | } |
| 10317 | } else { |
| 10318 | assert(NumRight < NumLeft); |
| 10319 | // Consider moving the last element on the left to the right side. |
| 10320 | CaseCluster &CC = *LastLeft; |
| 10321 | unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); |
| 10322 | unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); |
| 10323 | if (RightSideRank <= LeftSideRank) { |
| 10324 | // Moving the cluster to the right does not demot it. |
| 10325 | --LastLeft; |
| 10326 | --FirstRight; |
| 10327 | continue; |
| 10328 | } |
| 10329 | } |
| 10330 | } |
| 10331 | break; |
| 10332 | } |
| 10333 | |
| 10334 | assert(LastLeft + 1 == FirstRight); |
| 10335 | assert(LastLeft >= W.FirstCluster); |
| 10336 | assert(FirstRight <= W.LastCluster); |
| 10337 | |
| 10338 | // Use the first element on the right as pivot since we will make less-than |
| 10339 | // comparisons against it. |
| 10340 | CaseClusterIt PivotCluster = FirstRight; |
| 10341 | assert(PivotCluster > W.FirstCluster); |
| 10342 | assert(PivotCluster <= W.LastCluster); |
| 10343 | |
| 10344 | CaseClusterIt FirstLeft = W.FirstCluster; |
| 10345 | CaseClusterIt LastRight = W.LastCluster; |
| 10346 | |
| 10347 | const ConstantInt *Pivot = PivotCluster->Low; |
| 10348 | |
| 10349 | // New blocks will be inserted immediately after the current one. |
| 10350 | MachineFunction::iterator BBI(W.MBB); |
| 10351 | ++BBI; |
| 10352 | |
| 10353 | // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, |
| 10354 | // we can branch to its destination directly if it's squeezed exactly in |
| 10355 | // between the known lower bound and Pivot - 1. |
| 10356 | MachineBasicBlock *LeftMBB; |
| 10357 | if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && |
| 10358 | FirstLeft->Low == W.GE && |
| 10359 | (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { |
| 10360 | LeftMBB = FirstLeft->MBB; |
| 10361 | } else { |
| 10362 | LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); |
| 10363 | FuncInfo.MF->insert(BBI, LeftMBB); |
| 10364 | WorkList.push_back( |
| 10365 | {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); |
| 10366 | // Put Cond in a virtual register to make it available from the new blocks. |
| 10367 | ExportFromCurrentBlock(Cond); |
| 10368 | } |
| 10369 | |
| 10370 | // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a |
| 10371 | // single cluster, RHS.Low == Pivot, and we can branch to its destination |
| 10372 | // directly if RHS.High equals the current upper bound. |
| 10373 | MachineBasicBlock *RightMBB; |
| 10374 | if (FirstRight == LastRight && FirstRight->Kind == CC_Range && |
| 10375 | W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { |
| 10376 | RightMBB = FirstRight->MBB; |
| 10377 | } else { |
| 10378 | RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); |
| 10379 | FuncInfo.MF->insert(BBI, RightMBB); |
| 10380 | WorkList.push_back( |
| 10381 | {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); |
| 10382 | // Put Cond in a virtual register to make it available from the new blocks. |
| 10383 | ExportFromCurrentBlock(Cond); |
| 10384 | } |
| 10385 | |
| 10386 | // Create the CaseBlock record that will be used to lower the branch. |
| 10387 | CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, |
| 10388 | getCurSDLoc(), LeftProb, RightProb); |
| 10389 | |
| 10390 | if (W.MBB == SwitchMBB) |
| 10391 | visitSwitchCase(CB, SwitchMBB); |
| 10392 | else |
| 10393 | SL->SwitchCases.push_back(CB); |
| 10394 | } |
| 10395 | |
| 10396 | // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb |
| 10397 | // from the swith statement. |
| 10398 | static BranchProbability scaleCaseProbality(BranchProbability CaseProb, |
| 10399 | BranchProbability PeeledCaseProb) { |
| 10400 | if (PeeledCaseProb == BranchProbability::getOne()) |
| 10401 | return BranchProbability::getZero(); |
| 10402 | BranchProbability SwitchProb = PeeledCaseProb.getCompl(); |
| 10403 | |
| 10404 | uint32_t Numerator = CaseProb.getNumerator(); |
| 10405 | uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); |
| 10406 | return BranchProbability(Numerator, std::max(Numerator, Denominator)); |
| 10407 | } |
| 10408 | |
| 10409 | // Try to peel the top probability case if it exceeds the threshold. |
| 10410 | // Return current MachineBasicBlock for the switch statement if the peeling |
| 10411 | // does not occur. |
| 10412 | // If the peeling is performed, return the newly created MachineBasicBlock |
| 10413 | // for the peeled switch statement. Also update Clusters to remove the peeled |
| 10414 | // case. PeeledCaseProb is the BranchProbability for the peeled case. |
| 10415 | MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( |
| 10416 | const SwitchInst &SI, CaseClusterVector &Clusters, |
| 10417 | BranchProbability &PeeledCaseProb) { |
| 10418 | MachineBasicBlock *SwitchMBB = FuncInfo.MBB; |
| 10419 | // Don't perform if there is only one cluster or optimizing for size. |
| 10420 | if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || |
| 10421 | TM.getOptLevel() == CodeGenOpt::None || |
| 10422 | SwitchMBB->getParent()->getFunction().hasMinSize()) |
| 10423 | return SwitchMBB; |
| 10424 | |
| 10425 | BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); |
| 10426 | unsigned PeeledCaseIndex = 0; |
| 10427 | bool SwitchPeeled = false; |
| 10428 | for (unsigned Index = 0; Index < Clusters.size(); ++Index) { |
| 10429 | CaseCluster &CC = Clusters[Index]; |
| 10430 | if (CC.Prob < TopCaseProb) |
| 10431 | continue; |
| 10432 | TopCaseProb = CC.Prob; |
| 10433 | PeeledCaseIndex = Index; |
| 10434 | SwitchPeeled = true; |
| 10435 | } |
| 10436 | if (!SwitchPeeled) |
| 10437 | return SwitchMBB; |
| 10438 | |
| 10439 | LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " |
| 10440 | << TopCaseProb << "\n" ); |
| 10441 | |
| 10442 | // Record the MBB for the peeled switch statement. |
| 10443 | MachineFunction::iterator BBI(SwitchMBB); |
| 10444 | ++BBI; |
| 10445 | MachineBasicBlock *PeeledSwitchMBB = |
| 10446 | FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); |
| 10447 | FuncInfo.MF->insert(BBI, PeeledSwitchMBB); |
| 10448 | |
| 10449 | ExportFromCurrentBlock(SI.getCondition()); |
| 10450 | auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; |
| 10451 | SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, |
| 10452 | nullptr, nullptr, TopCaseProb.getCompl()}; |
| 10453 | lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); |
| 10454 | |
| 10455 | Clusters.erase(PeeledCaseIt); |
| 10456 | for (CaseCluster &CC : Clusters) { |
| 10457 | LLVM_DEBUG( |
| 10458 | dbgs() << "Scale the probablity for one cluster, before scaling: " |
| 10459 | << CC.Prob << "\n" ); |
| 10460 | CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); |
| 10461 | LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n" ); |
| 10462 | } |
| 10463 | PeeledCaseProb = TopCaseProb; |
| 10464 | return PeeledSwitchMBB; |
| 10465 | } |
| 10466 | |
| 10467 | void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { |
| 10468 | // Extract cases from the switch. |
| 10469 | BranchProbabilityInfo *BPI = FuncInfo.BPI; |
| 10470 | CaseClusterVector Clusters; |
| 10471 | Clusters.reserve(SI.getNumCases()); |
| 10472 | for (auto I : SI.cases()) { |
| 10473 | MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; |
| 10474 | const ConstantInt *CaseVal = I.getCaseValue(); |
| 10475 | BranchProbability Prob = |
| 10476 | BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) |
| 10477 | : BranchProbability(1, SI.getNumCases() + 1); |
| 10478 | Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); |
| 10479 | } |
| 10480 | |
| 10481 | MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; |
| 10482 | |
| 10483 | // Cluster adjacent cases with the same destination. We do this at all |
| 10484 | // optimization levels because it's cheap to do and will make codegen faster |
| 10485 | // if there are many clusters. |
| 10486 | sortAndRangeify(Clusters); |
| 10487 | |
| 10488 | // The branch probablity of the peeled case. |
| 10489 | BranchProbability PeeledCaseProb = BranchProbability::getZero(); |
| 10490 | MachineBasicBlock *PeeledSwitchMBB = |
| 10491 | peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); |
| 10492 | |
| 10493 | // If there is only the default destination, jump there directly. |
| 10494 | MachineBasicBlock *SwitchMBB = FuncInfo.MBB; |
| 10495 | if (Clusters.empty()) { |
| 10496 | assert(PeeledSwitchMBB == SwitchMBB); |
| 10497 | SwitchMBB->addSuccessor(DefaultMBB); |
| 10498 | if (DefaultMBB != NextBlock(SwitchMBB)) { |
| 10499 | DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, |
| 10500 | getControlRoot(), DAG.getBasicBlock(DefaultMBB))); |
| 10501 | } |
| 10502 | return; |
| 10503 | } |
| 10504 | |
| 10505 | SL->findJumpTables(Clusters, &SI, DefaultMBB); |
| 10506 | SL->findBitTestClusters(Clusters, &SI); |
| 10507 | |
| 10508 | LLVM_DEBUG({ |
| 10509 | dbgs() << "Case clusters: " ; |
| 10510 | for (const CaseCluster &C : Clusters) { |
| 10511 | if (C.Kind == CC_JumpTable) |
| 10512 | dbgs() << "JT:" ; |
| 10513 | if (C.Kind == CC_BitTests) |
| 10514 | dbgs() << "BT:" ; |
| 10515 | |
| 10516 | C.Low->getValue().print(dbgs(), true); |
| 10517 | if (C.Low != C.High) { |
| 10518 | dbgs() << '-'; |
| 10519 | C.High->getValue().print(dbgs(), true); |
| 10520 | } |
| 10521 | dbgs() << ' '; |
| 10522 | } |
| 10523 | dbgs() << '\n'; |
| 10524 | }); |
| 10525 | |
| 10526 | assert(!Clusters.empty()); |
| 10527 | SwitchWorkList WorkList; |
| 10528 | CaseClusterIt First = Clusters.begin(); |
| 10529 | CaseClusterIt Last = Clusters.end() - 1; |
| 10530 | auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); |
| 10531 | // Scale the branchprobability for DefaultMBB if the peel occurs and |
| 10532 | // DefaultMBB is not replaced. |
| 10533 | if (PeeledCaseProb != BranchProbability::getZero() && |
| 10534 | DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) |
| 10535 | DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); |
| 10536 | WorkList.push_back( |
| 10537 | {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); |
| 10538 | |
| 10539 | while (!WorkList.empty()) { |
| 10540 | SwitchWorkListItem W = WorkList.back(); |
| 10541 | WorkList.pop_back(); |
| 10542 | unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; |
| 10543 | |
| 10544 | if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && |
| 10545 | !DefaultMBB->getParent()->getFunction().hasMinSize()) { |
| 10546 | // For optimized builds, lower large range as a balanced binary tree. |
| 10547 | splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); |
| 10548 | continue; |
| 10549 | } |
| 10550 | |
| 10551 | lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); |
| 10552 | } |
| 10553 | } |
| 10554 | |